如何正确链接一个C++库,该库的行为取决于其编译方式?

huangapple go评论65阅读模式
英文:

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 as static.

This way, it can be included in any .cpp file, and be compiled with the options it defined without affecting other compilations.

huangapple
  • 本文由 发表于 2023年5月18日 04:10:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定