簡體   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 的情況?

為此,您不一定需要宏。 您可以在情況 A 中使用 1.cpp 編譯和鏈接,在情況 B 中使用 2.cpp 編譯和鏈接。

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 ()

除了選項之外,您還可以有其他一些條件。 這對於將 API 移植到不同系統通常很有用。


但基於宏的解決方案也有效:

// 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

在這種方法中,只需始終編譯兩個源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM