【问题标题】:C: Linking error for function of same signature [duplicate]C:相同签名功能的链接错误[重复]
【发布时间】:2021-02-09 11:28:07
【问题描述】:

我在运行程序时遇到链接错误,即使 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

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

谢谢

【问题讨论】:

    标签: c linker linker-errors


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-09-29
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        相关资源
        最近更新 更多