如果main.c
和test.c
是单独的翻译单元,那么您应该是正确的。但是,通过将test.c
的文本直接包含到main.c
中,您创建了一个单个转换单元,因此对于main
可以看到静态函数。它的行为好像你已经将它全部写入一个文件一样。
你不想#include
包含变量或函数的文件定义;这是在编译或链接时遇到多个定义错误的好方法。相反,#include
文件的内容应限于类型定义,非定义变量声明和函数声明。
如下您可以创建一个文件test.h
:
#ifndef TEST_H // include guard; prevents this file from being processed
#define TEST_H // more than once per translation unit
void foo(); // declaration for foo; this is the only function we're exposing
#endif
然后重写main.c
作为
#include "test.h"
int main(void)
{
test();
return 0;
}
你会再编译main.c
和test.c
分开,然后链接生成的目标文件来创建可执行文件:
gcc -c main.c
gcc -c test.c
gcc -o test main.o test.o
此时您将沿着“未定义参考”的顺序收到链接器错误,因为test
的符号尚未导出。
是的,这是因为包括。您应该只包含头文件'.h'。 – jweyrich
@jweyrich:真的吗?预处理器对符号一无所知,它只是解析由chars组成的令牌。你能否解释一下#include一个c文件与直接粘贴它的内容有什么不同? –
@flix请尝试仅包含* .h文件而非* .c文件。 – Allwyn