C: 相同签名函数的链接错误

C: Linking error for function of same signature

当我 运行 我的程序时出现链接错误,即使 test.h 和 test.c 中的两个函数的函数签名相同:

test.h :

void function(int);

test.c :

#include "test.h"
#include "stdio.h"

static void function(int n) {
    printf("%d\n", n);
}

main.c :

#include "test.h"

int main() {

    function(5);
    return 0;
}

这是输出:

Undefined symbols for architecture x86_64:
  "_function", referenced from:
      _main in ccNaA2H2.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

在class中了解到函数签名就是函数名及其参数。 那么,为什么我的程序在 main 中调用 function(5) in test.h 而它将调用 function(5) in test.c 呢?

谢谢

static at global scope (outside of functions) 意味着它只在这个文件中可见(它有内部链接)。因此,test.c 中的 static void function(int n) 在 main.c 中不可见。

对于main中的调用function(5);,编译器看到test.h中的函数原型,但是链接器找不到它的实现,因为c文件中的函数是static.

解决方法:如果您想在不同的文件中使用该函数,请删除单词 static

test.c 中,您将函数声明为 static,这意味着它在该模块外不可见。删除 static 关键字。