我的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;
}
答案 0 :(得分:1)
如果函数声明为static
,则该函数位于文件范围中,表示该函数的范围仅限于转换单元(在本例中为源文件) )。同一编译单元中存在的其他函数可以调用函数,但编译单元外部没有的函数可以看到定义(存在)或调用函数。
相关:来自C11
标准文件,章节,标识符的链接
如果对象或函数的文件范围标识符的声明包含存储类说明符
static
,则标识符具有内部链接。(30)
和脚注(30),
函数声明只有在文件范围内时才能包含存储类说明符
static
;
解决方案:删除函数定义和声明中的static
。
FWIW,将static
函数的前向声明放在头文件中没有多大意义。无论如何,无法从其他源文件中调用static
函数。