我正在构建一个当前只包含单个目标文件的小型静态库。当我尝试将它链接到程序时,我得到一系列“未定义的引用”错误。所有错误似乎都与.cpp文件中的定义有关。
库头文件(except.hpp)是:
#ifndef FOD_REEF_EXCEPT
#define FOD_REEF_EXCEPT
#include <exception>
#include <string>
namespace REEF
{
class REEFException : public std::exception
{
public:
REEFException() = default;
REEFException(const char* file, int line);
virtual ~REEFException() = default;
virtual const char* what() const noexcept;
virtual const std::string What() const noexcept { return std::string(what()); }
virtual const std::string Where() const noexcept;
private:
std::string _where;
};
}
#endif // FOD_REEF_EXCEPT
实现文件(except.cpp)是:
#include "except.hpp"
const char* defaultExceptionMessage = "Undefined exception";
REEF::REEFException::REEFException(const char* file, int line)
{
_where = "line " + std::to_string(line) + " in " + file;
}
const char* REEF::REEFException::what() const noexcept
{
return defaultExceptionMessage;
}
const std::string REEF::REEFException::Where() const noexcept
{
return _where;
}
我使用:
编译目标文件(except.o)g++ -c -std=c++17 -Wall -Wextra -I~/dev/project/fod -o obj/except.o src/except.cpp
然后使用:
创建一个库ar rvs bin/libreef.a obj/except.o
这成功创建了〜/ dev / project / fod / reef / bin / libreef.a。运行ar -t libreef.a显示
except.o
当我使用
从不同的目录编译测试程序时g++ -std=c++17 -Wall -Wextra -I~/dev/project/fod -L~/dev/project/fod/reef/bin -lreef src/test.cpp -o bin/test
我得到一系列未定义的引用错误:
test.cpp:46: undefined reference to `REEF::REEFException::REEFException(char const*, int)'
test.cpp:46: undefined reference to `typeinfo for REEF::REEFException'
/tmp/ccrlvFmY.o: In function `TestAsserts()':
test.cpp:133: undefined reference to `REEF::REEFException::REEFException(char const*, int)'
test.cpp:133: undefined reference to `typeinfo for REEF::REEFException'
test.cpp:135: undefined reference to `REEF::REEFException::REEFException(char const*, int)'
test.cpp:135: undefined reference to `typeinfo for REEF::REEFException'
/tmp/ccrlvFmY.o: In function `REEF::REEFException::REEFException()':
except.hpp:46: undefined reference to `vtable for REEF::REEFException'
/tmp/ccrlvFmY.o: In function `REEF::REEFException::~REEFException()':
except.hpp:59: undefined reference to `vtable for REEF::REEFException'
/tmp/ccrlvFmY.o:(.gcc_except_table+0x6c): undefined reference to `typeinfo for REEF::REEFException'
/tmp/ccrlvFmY.o:(.gcc_except_table+0xb0): undefined reference to `typeinfo for REEF::REEFException'
但是,如果我不对库进行编译,而是直接针对except.o编译,就像这样
g++ -std=c++17 -Wall -Wextra -I~/dev/project/fod src/test.cpp ../obj/except.o -o bin/test
从测试目录然后编译并运行就好了。
我无法解决为什么链接库是一个问题,它只是对象文件的容器不是吗?我知道链接器正在找到正确的库文件,因为如果我更改它的名称,我会收到一条错误,指出它无法找到。
任何人都可以帮助我吗?我没有更多的头发可以丢失。