我的 Geany 项目有一个奇怪的问题。该项目非常简单,包含 3 个文件,均位于同一目录中:main.c
、foo.h
和 foo.c
。
编译器错误:
In file included from main.c:1:0:
foo.h:4:12: warning: ‘bar’ used but never defined
static int bar(void);
^
/tmp/cc0zCvOX.o: In function `main':
main.c:(.text+0x12): undefined reference to `bar'
Compilation failed.
collect2: error: ld returned 1 exit status
出了什么问题?
main.c:
#include "foo.h"
int main(int argv, char* argc[])
{
bar();
return 0;
}
foo.h:
#ifndef _FOO_H_
#define _FOO_H_
static int bar(void);
#endif // _FOO_H_
foo.c:
#include "foo.h"
#include <stdio.h>
static int bar(void)
{
printf("Hello World\n");
return 1;
}
最佳答案
如果函数被声明为static
,则该函数位于文件范围中,意味着该函数的范围仅限于翻译单元(在这种情况下,源文件)。存在于同一编译单元中的其他函数可以调用该函数,但存在于编译单元之外的函数无法看到定义(存在)或调用该函数。
相关:来自C11
标准文档,章节,标识符的链接
If the declaration of a file scope identifier for an object or a function contains the storage class specifier
static
, the identifier has internal linkage.(30)
以及脚注 (30),
A function declaration can contain the storage-class specifier
static
only if it is at file scope;
解决方案:去掉函数定义和声明中的static
。
FWIW,将 static
函数的前向声明放在头文件中没有多大意义。无论如何,static
函数不能从其他源文件调用。
关于c - Geany 项目包含编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29959407/