c - 将 .c 文件设为库错误

标签 c

我有一个 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文件无法正确运行。

有人可以帮我解决这个问题吗?非常感谢!

最佳答案

您的问题是:

  1. test.c 中调用了 bar()
  2. test.c 没有任何 bar 声明,也没有声明 .h 文件的 #include
  3. 您不得以任何方式更改 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/

相关文章:

c - strace如何读取系统调用sys_open的文件名?

c - 登录进程作为协进程

c - 为什么它说 'expected declaration specifiers before ' main''

C:将最小 32 位整数 (-2147483648) 转换为 float 给出正数 (2147483648.0)

c++ - MinGW 不喜欢评论

c - 简单排列,无需重复

c++ - C 和汇编程序实际上编译成什么?

使用 fgetc/getc 后无法写入文件 (Windows)

c - 生产者/消费者使用信号量

c - 替换c字符串中的最后一个单词