我无法使我的程序正常工作,但我始终得到未定义的符号:c

时间:2019-12-05 08:20:27

标签: c++ linux systems-programming

我试图加载所有库,并从每个库中调用一个函数,以创建文件并通过指针填充小提琴,并使用它们在主程序中写入内容,然后关闭它们。

这是我的主要功能:

#include <dlfcn.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

char LIBA[]="./LIBA.SO";
char LIBB[]="./LIBB.SO";
char LIBC[]="./LIBC.SO";
typedef void (*FUNC_T)(int*);
FUNC_T FUNC[2];

void ifnull(void *detect)
{
    if (detect == NULL)
    {
        cout << "ERROR:" << dlerror() << endl;
        exit(-1);    
    }
}

void ifnull2(FUNC_T detect)
{
    if (detect == NULL)
    {
        cout << "ERROR:" << dlerror() << endl;
       exit(-1);    
    }
}

int main()
{
    void *handle[2];
    int FD[2];
    handle[0]=dlopen(LIBA, RTLD_LAZY); ifnull(handle[0]);
    handle[1]=dlopen(LIBB, RTLD_NOW); ifnull(handle[1]);
    handle[2]=dlopen(LIBC, RTLD_NOW); ifnull(handle[2]);        
    FUNC[0]=(void(*)(int*))dlsym(handle[0], "c"); ifnull2(FUNC[0]);
    FUNC[1]=(void(*)(int*))dlsym(handle[1], "c"); ifnull2(FUNC[1]);
    FUNC[2]=(void(*)(int*))dlsym(handle[2], "c"); ifnull2(FUNC[2]);

    FUNC[0](&FD[0]); FUNC[1](&FD[1]); FUNC[2](&FD[2]);

    return 0;
}

这是在libs内部:

#include <stdio.h>

void c(int *fd)
{
    printf("ok A\n");
}

我不断得到

ERROR:./LIBA.SO: undefined symbol: c

请帮助

1 个答案:

答案 0 :(得分:1)

C ++蒙上了函数名称,因为它可以具有多个具有相同名称的函数。

所以,对于

#include <stdio.h>

void c(int *fd)
{
    printf("ok A\n");
}

我们得到

$ g++ -Wall -Wextra -pedantic -c -fPIC liba.cpp -o liba.so
liba.cpp: In function ‘void c(int*)’:
liba.cpp:3:13: warning: unused parameter ‘fd’ [-Wunused-parameter]
 void c(int *fd)
             ^~

$ nm liba.so
                 U _GLOBAL_OFFSET_TABLE_
                 U puts
0000000000000000 T _Z1cPi

如您所见,该函数以_Z1cPi的形式存在。我不确定这是否可以安全使用。但是,您可以使用extern "C"

对于

#include <stdio.h>

extern "C" void c(int *fd)
{
    printf("ok A\n");
}

我们得到

$ g++ -Wall -Wextra -pedantic -c -fPIC liba.cpp -o liba.so
liba.cpp: In function ‘void c(int*)’:
liba.cpp:3:24: warning: unused parameter ‘fd’ [-Wunused-parameter]
 extern "C" void c(int *fd)
                        ^~

$ nm liba.so
0000000000000000 T c
                 U _GLOBAL_OFFSET_TABLE_
                 U puts