2015-04-30 120 views
0

我在我的Geany项目中有一个奇怪的问题。该项目非常简单,包含3个文件,全部位于同一目录中:main.cfoo.hfoo.cGeany项目包括编译器错误

编译器错误:

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

项目不包括gcc的正确调用。请更新Build-> Set Build命令和/或考虑使用makefile。您首先要编译foo.c并将其设为目标文件,而不是编译main.c.也许预编译foo.c的命令对你来说效果不错,但是你必须证明它。 – frlan

回答

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函数不能从其他源文件中调用。

+0

我已经删除了'static',它仍然会提示未定义的参考栏。有趣的是,如果我将bar的定义移动到foo.h(来自foo.c),它会进行编译。这意味着foo.c不包括在Geany项目中吗? –

+0

@JakeM也从头文件中删除'static'。而且你没有在头文件中定义函数。也许在这种情况下,你是对的,出于某种原因,'foo.c'没有被编译并且与'main.c'链接。请检查。 –

+0

我已经从两个文件中删除了'static'。你如何将foo.c添加到Geany项目中?我google了这个和一个stackoverflow答案说你不需要自动链接,但也许这是不正确的? –