c - Geany 项目包含编译器错误

标签 c gcc static undefined-reference geany

我的 Geany 项目有一个奇怪的问题。该项目非常简单,包含 3 个文件,均位于同一目录中:main.cfoo.hfoo.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

出了什么问题?

ma​​in.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/

相关文章:

java - Eclipse - 将鼠标悬停在标记上时的自定义文本

c - 在函数调用中省略 & 符号

c - 重置/清除指向结构的全局指针数组

c - 用 C 获得整数中最正确数字的最佳方法是什么?

c - GCC宏扩展调用另一个宏

c - 我是否误解了 GCC 中的 __attribute__ ((packed)) ?

c - 如何固定结构的分配大小

iphone - 从静态 TableView 中获取标题标题

java - 为什么在静态上下文中访问实例化字段比在 JAVA 中访问实例化上下文更快

c# - 是否固定了静态类成员?