我有一些用于除錯的代碼,不希望出現在版本中。
我可以macros用來注釋掉它們嗎?
例如:
#include <iostream>
#define p(OwO) std::cout << OwO
#define DEBUG 1 // <---- set this to -1 in release mode
#if DEBUG == 1
#define DBUGstart
#define DBUGend
// ^ is empty when in release mode
#else
#define DBUGstart /*
#define DBUGend */
/*
IDE(and every other text editor, including Stack overflow) comments the above piece of code,
problem with testing this is my project takes a long
time to build
*/
#endif
int main() {
DBUGstart;
p("<--------------DEBUG------------->\n");
// basically commenting this line in release mode, therefore, removing it
p("DEBUG 2\n");
p("DEBUG 3\n");
DBUGend;
p("Hewwo World\n");
return 0x45;
}
對于單行除錯,我可以輕松地執行以下操作:
#include <iostream>
#define DEBUG -1 // in release mode
#define p(OwO) std::cout << OwO
#if DEBUG == 1
#define DB(line) line
#else
#define DB(line)
#endif
int main()
{
DB(p("Debug\n"));
p("Hewwo World");
return 0x45;
}
但我想這對于多行會有點混亂
我正在使用 MSVC (Visual Studio 2019),如果這不起作用,那么是否還有其他實作相同的方法(對于多行,單行非常簡單)?
uj5u.com熱心網友回復:
你正在使這不必要地復雜化。
如果在 Release 中,則不是有條件地插入 C 樣式的注釋,而是僅在 Debug 中插入代碼。Visual Studio_DEBUG默認在除錯配置中定義,因此您可以像下面這樣使用它:
#include <iostream>
int main() {
std::cout << "hello there. \n";
#ifdef _DEBUG
std::cout << "this is a debug build.";
#endif
}
uj5u.com熱心網友回復:
為此,您甚至不需要宏。條件編譯直接融入語言:
#include <iostream>
constexpr bool gDebug = true;
int foo();
int main() {
std::cout << "hello there.\n";
int foo_res = foo();
if constexpr (gDebug) {
std::cout << "Foo returned: " << foo_res << "\n";
}
}
這具有直接的好處,即即使在編譯出代碼時仍然檢查代碼是否有效。
它還可以干凈地處理僅在除錯中需要的變數,這在使用基于宏的條件編譯時通常會導致僅發布警告訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337183.html
上一篇:使用字典回圈定義tkentry
