'undefined reference to function' 尝试使用 header 构建一个重新定义函数名称的程序

'undefined reference to function' while trying to build a program with header that redefines function names

我遇到的问题与提出此问题的人完全相同:How to hide the exported symbols name within a shared library

我决定按照 Alexander 给出的说明进行操作(第 3 个答案),但是在将生成的 header 包含到我的 C 主程序中之后,我得到了错误 undefined reference to function

head.h

#define SecretFunc1 abab

application.c

#include <stdio.h>
#include "head.h"

int main(){
    SecretFunc1();
    return 0;   
}

libdyn.c

#include <stdio.h>
int SecretFunc1(){
    return 2
}

我已经将动态库构建到 .so 文件中,然后在尝试使用以下方法构建应用程序之后: gcc app.c -L<path> -ldyn -o sample 在函数 main 中未定义引用 abab

我真的不知道该怎么办。

(部分)预处理后,您的 application.c 将如下所示:

#include <stdio.h>

int main(){
    abab();
    return 0;   
}

首先,这应该给您一个警告,即 abab 是隐式声明的,这通常不是一个好主意。您应该声明该函数(在 application.clibdyn.c 共享的头文件中):

int SecretFunc1(void);

编译为目标文件时,此目标文件将引用符号 abab

编译libdyn.c为目标文件后,会提供一个名为SecretFunc1的符号。因此,链接器不会将其与 application.o.

中的引用 abab 匹配

您需要在所有使用它的文件中重命名该函数,例如通过在 libdyn.c 中包含 head.h 或更好地将重命名宏和声明放在 libdyn.h 中,该 libdyn.h 包含在 libdyn.capplication.c 中。