如何解决构建的 .so 文件中未定义的符号错误



我想在 Ubuntu16.04 中构建一个 .so 文件。gcc 的版本是:

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11)

我在同一目录中有student_info.cpp,student_info.hMakefile
student_info.h的内容是:

#include <iostream>
using namespace std;
class student_info
{
public:
    student_info();
private:
    char* name;
    int score;
public:
    void setName(char* name)
    {
        this->name = name;
    }
    void setScore(int score)
    {
        this->score = score;
    }
    char* getName()
    {
        return this->name;
    }
    int getScore()
    {
        return this->score;
    }
};

student_info.cpp是:

#include <iostream>
#include "student_info.h"
using namespace std;
extern "C"
{
    student_info* student_info_new() {return new student_info();}
}

而制作文件是:

student_info.so: student_info.cpp student_info.h
    g++ -std=c++11 -shared -fPIC -o student_info.so student_info.cpp

执行make命令后。我明白了student_info。但是使用ldd -r student_info.so后,我得到以下错误:

linux-vdso.so.1 =>  (0x00007fff269fa000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f2111228000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f2111012000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2110c48000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f211093f000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f21117ac000)
undefined symbol: _ZN12student_infoC1Ev (./student_info.so)

如何解决此未定义的符号错误?谢谢。

ldd表示student_info的默认构造函数是未定义的。您需要在 student_info.hstudent_info.cpp 中提供默认构造函数的定义。例如:

class student_info
{
public:
    student_info() : name(), score() {} // Declaration and definition.
private:
    char* name;
    int score;
// ...
};

最新更新