简体   繁体   English

C++如何在使用相同的.h时使用相同的.h并选择不同的.cpp?

[英]C++ how can i use the same .h and choose different .cpp when using the same .h?

这里的场景是:“baselogger.h”包含API,我在两种情况下实现这些API(case A和case B,A对应1.cpp,B对应2.cpp),那么如何编写宏来编译不同的使用不同的 cpp 在“baselogger.h”中实现 API 的情况?

You don't necessarily need a macro for this.为此,您不一定需要宏。 You could instead compile and link with 1.cpp in case A and compile and link with 2.cpp in case B.您可以在情况 A 中使用 1.cpp 编译和链接,在情况 B 中使用 2.cpp 编译和链接。

CMake example: CMake 示例:

option (CASE_A "Descriptive description" ON)
if (CASE_A)
    target_sources(target_name PRIVATE 1.cpp)
else ()
    target_sources(target_name PRIVATE 2.cpp)
endif ()

Insted of option, you can have some other condition.除了选项之外,您还可以有其他一些条件。 This is often useful for porting API to different systems.这对于将 API 移植到不同系统通常很有用。


But a macro based solution works too:但基于宏的解决方案也有效:

// 1.cpp
#ifdef MACRO_CASE_A
// case A implementation for baselogger.h
#endif

// 2.cpp
#ifndef MACRO_CASE_A
// case B implementation for baselogger.h
#endif

In this approach, simply compile both sources always.在这种方法中,只需始终编译两个源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM