首页 > 解决方案 > C:相同签名功能的链接错误

问题描述

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

测试.h:

void function(int);

测试.c:

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

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

主.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

在课堂上,我了解到函数签名是函数名及其参数。那么,为什么我在 main 中的程序不调用 test.h 中的 function(5) 来调用 test.c 中的 function(5) 呢?

谢谢

标签: clinkerlinker-errors

解决方案


static在全局范围内(函数之外)意味着它仅在此文件中可见(它具有内部链接)。因此,static void function(int n)从 main.c 中看不到 in test.c。

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

static解决方案:如果您想在不同的文件中使用该功能,请删除单词。


推荐阅读