首页 > 解决方案 > 在 C 中的文件之间切换函数

问题描述

嘿,我尝试使用另一个文件的功能,这不是问题,但是如果我也想使用另一个文件的功能,我会遇到问题:

测试1.c

#include "test2.c"

int func1(int a, int b){
    return func2(a, b);
}

测试2.c

#include "test1.c"

int func2(int a, int b){
     return a + b;
}

int main(void){
     func1(10, 5);
}

这可行,但如果我收到错误,则包含包含语句的页面。有没有人知道如何解决这个问题?

标签: cinclude

解决方案


通常,您不应在其他 C 源文件中包含 C 源文件。在您的特定情况下,您创建了一个依赖循环:test1.c 包含 test2.c,其中再次包含 test1.c,其中包含 test2.c ...相反,在头文件中声明函数原型并包含这些:

测试1.h:

#ifndef TEST1_H
#define TEST1_H
int func2(int a, int b);
#endif

测试2.h

#ifndef TEST2_H
#define TEST2_H
int func2(int a, int b);
#endif

现在您可以包含test2.hintest1.ctest1.hin test2.c。或者,您可以声明 in 的原型,func1反之亦然test2.c,但在我看来,使用头文件是更简洁的解决方案。


推荐阅读