如果我将其内联,链接器错误就会消失。这不是我想要依赖的东西,因为内联是一个请求而不是保证。
内联函数就可以了。
即使目标代码未内联,只要函数在不同的翻译单元中未以某种方式更改,语言也保证不会导致链接器错误或未定义的行为。
If you #include
数百个 .cpp 文件中的 .hpp,您可能会注意到代码有点膨胀,但程序仍然是正确的。
是什么导致了这种行为?我不是在处理返回某种单例的情况。
The #include
机制可以方便地减少您必须在具有确切内容的多个文件中手动创建的代码量。最后,所有翻译单元#include
其他文件从它们的文件中获取代码行#include
.
If you #include
file_ops.hpp 在 file1.cpp 和 file2.cpp 中,就好像您有:
文件1.cpp:
bool systemIsLittleEndian() {
uint16_t x = 0x0011;
uint8_t *half_x = (uint8_t *) &x;
if (*half_x == 0x11)
return true;
else
return false;
}
文件2.cpp:
bool systemIsLittleEndian() {
uint16_t x = 0x0011;
uint8_t *half_x = (uint8_t *) &x;
if (*half_x == 0x11)
return true;
else
return false;
}
当您编译这两个 .cpp 文件并将它们链接在一起以创建可执行文件时,链接器会注意到名为的函数有两个定义systemIsLittleEndian
。这就是链接器错误的根源。
一种解决方案,无需使用inline
解决您的问题的一种方法,无需使用inline
, is:
- 在 .hpp 文件中声明该函数。
- 在适当的 .cpp 文件中定义它。
文件操作.hpp:
bool systemIsLittleEndian(); // Just the declaration.
文件操作.cpp:
#include "file_ops.hpp"
// The definition.
bool systemIsLittleEndian() {
uint16_t x = 0x0011;
uint8_t *half_x = (uint8_t *) &x;
if (*half_x == 0x11)
return true;
else
return false;
}
Update
关于
bool MY_LIB_EXPORT someFunc();// implemented in `file_ops.cpp`
网络上有很多相关信息。这是 Microsoft/Windows 问题。以下是了解它的几个起点。
- 使用 __declspec(dllexport) 从 DLL 导出 https://msdn.microsoft.com/en-us/library/a90k134d.aspx
- 使用 __declspec(dllimport) 导入到应用程序中 https://msdn.microsoft.com/en-us/library/8fskxacy.aspx