英文:
How to correctly link a C++ library that has different behaviors depending on its compilation?
问题
I have a library called Print
and the function println
, which mimics printf
. If compiled with the directive USE_DEBUG_PRINT
, println
actually prints something. If compiled without this define, it prints nothing.
Then I want to use this library inside another library, let's call it A
. A
uses Print
with this directive defined. Another library, 'B', uses 'Print' without this directive, so println
has different behaviors for them.
However, when compiling into an application, depending on the link order, B
will use println
from A
, or the opposite. This happens because the println
symbol is defined for both of the libs, so the linker just picks the first.
How can I, instead, make Print
"private" for these libs? I don't want anyone using A
or B
to have access to the println
function regardless, so they can just be "merged" together, keeping println
out of the .txt
files, being used only in their implementations.
I'm using Clang and CMake to generate both libs and the app. Print
is an object library, while the other ones are static.
英文:
I have a library called Print
and the function println
, which mimics printf
. If compiled with the directive USE_DEBUG_PRINT
, println
actually prints something. If compiled without this define, it prints nothing.
Then I want to use this library inside another library, let's call it A
. A
uses Print
with this directive defined. Another library, 'B', uses 'Print' without this directive, so println
has different behaviors for them.
However, when compiling into an application, depending on the link order, B
will use println
from A
, or the opposite. This happens because the println
symbol is defined for both of the libs, so the linker just picks the first.
How can I, instead, make Print
"private" for these libs? I don't want anyone using A
or B
to have access to the println
function regardless, so they can just be "merged" together, keeping println
out of the 1.txt
files, being used only in their implementations.
I'm using Clang and CMake to generate both libs and the app. Print
is an object library, while the other ones are static.
答案1
得分: 0
以下是翻译好的部分:
我通过以下方式成功解决了这个问题:
Print
现在是一个接口,只包含一个头文件。println
被标记为static
。
这样,它可以被包含在任何 .cpp
文件中,并且可以使用它定义的选项进行编译,而不会影响其他编译。
英文:
I managed to solve this by doing the following:
- Print is now an interface, containing just a header file.
println
is marked asstatic
.
This way, it can be included in any .cpp
file, and be compiled with the options it defined without affecting other compilations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论