我有一个 test.c 文件,其中包含 main() 函数和一些测试用例,并且无法对其进行修改(例如添加“include *.h”)。然后我有一个 foo.c 文件,其中包含一些函数(没有 main() 函数)。这些功能将通过test.c文件中的测试用例进行测试。我要做的就是使用 foo.c 作为库并将其链接到 test.c 文件。这是简单的代码。
测试.c
//cannot modify
int main(){
...
bar();
...
}
foo.c
#include "foo.h" //I will explain this below.
int bar(){
...
}
我正在尝试使用.h文件实现一个接口(interface),例如
foo.h
#ifndef _FOO_H_
#define _FOO_H_
extern int bar();
#endif
然后使用命令行
gcc -c foo.c
gcc -o output test.c foo.o
./output
你可能会猜到结果。有警告“函数‘bar’的隐式声明在 C99 [-Wimplicit-function-declaration] 中无效”。并且test.c文件无法正确运行。
有人可以帮我解决这个问题吗?非常感谢!
最佳答案
您的问题是:
test.c
中调用了bar()
。test.c
没有任何bar
声明,也没有声明 .h 文件的#include
栏
。- 您不得以任何方式更改
test.c
以添加声明或 #include。
这是一个难题。 C 语言要求在test.c
中有一个bar
的原型(prototype)/声明!它可以直接写入 test.c
文件中(在调用它之前写入 extern int bar();
),或者声明可以从另一个带有#include
语句,但您必须拥有它。
幸运的是,GCC 有一种方法可以在编译文件时强制将 #include
语句添加到文件中。您不必更改 test.c
即可使其以 #include "foo.h"
开头。这将解决您的问题:
gcc -c -include foo.h test.c
关于c - 将 .c 文件设为库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974187/