内联方法作为共享库的符号不可用

inline methods not available as symbols of shared library

本文关键字:符号 共享 方法      更新时间:2023-10-16

如果我有一个类,它将被编译为共享对象。该类在.h文件中声明,并在.cpp文件中实现。

此类包含两个内联方法

如果我写了一些程序,链接到这个共享库并包含.h文件,链接时我会得到未定义的引用错误。

这是因为没有为内联方法导出符号吗?

我的理解正确吗?

更新:下面的一些示例代码

somelib.h

#ifndef __ABC_LIB_H
#define __ABC_LIB_H
#include <iostream>
class ABC {
    ABC();
    ~ABC();
    inline void not_callable_outside_library();
    void callable_outside_library();
};
#endif

somelib.cpp

#include "somelib.h"
ABC::ABC() {}
ABC::~ABC() {}
void ABC::not_callable_outside_library(){ std::cout<<"not_callable_outside_library"<<std::endl; }
void ABC::callable_outside_library(){ std::cout<<"callable_outside_library"<<std::endl; }

程序.cpp

#include "somelib.h"
int main() {
    ABC x;
    x.not_callable_outside_library();
    return 0;
};

将somelib.cpp编译为共享库(.so对象)并将其链接到program.cpp,然后获得名为program的二进制文件。

现在,链接时应该会得到一个未定义的引用

内联函数必须在头文件中定义。将您所拥有的与以下内容进行对比:

somelib.h:

#ifndef ABC_LIB_H
#define ABC_LIB_H
#include <iostream>
class ABC {
    ABC();
    ~ABC();
    void not_callable_outside_library();
    void callable_outside_library();
};
inline void ABC::not_callable_outside_library() {
    std::cout << "not_callable_outside_libraryn";
}
#endif

somelib.cpp:

#include "somelib.h"
ABC::ABC() { }
ABC::~ABC() { }
void ABC::callable_outside_library() {
    std::cout << "callable_outside_libraryn";
}

program.cpp:

#include "somelib.h"
int main() {
    ABC x;
    x.not_callable_outside_library();
}