gpt4 book ai didi

c++ - 可以做 "#ifdef DEBUG( ... ) __VA_ARGS__"吗?

转载 作者:行者123 更新时间:2023-11-28 00:47:35 25 4
gpt4 key购买 nike

全局.h

#ifndef GLOBAL_H
# define GLOBAL_H

#define DEBUG

#ifdef DEBUG
# define IF_DEBUG( ... ) __VA_ARGS__
#else
# define IF_DEBUG( ... )
#endif /* DEBUG */

#endif /* GLOBAL_H */

main.cpp

#include <string>
#include <iostream>
#include "Global.h"

int main() {
int A = 1;
int B = 2;
int C = 0;

IF_DEBUG(
std::cout << "\nStep 1> Calculating...\n";
)

C = A + B;

// DO WHATEVER

IF_DEBUG(
std::cout << "\nStep n> ...\n";
)

// ...

std::cout << C << std::endl;

// Note: I could also do some operations within the IF_DEBUG macro.
IF_DEBUG(
int X = 10;
int Y = 5;
int Z = X / Y;
std::cout << Z << std::endl;
)

IF_DEBUG(
std::cout << "\nDebugged! This program has been paused. Enter any key to continue!\n";
::getchar();
)
return 0;
}

你看到我如何在全局头文件 (Global.h) 中定义 IF_DEBUG 以及我如何不断使用它在主源文件 (Main.cpp) 中用于调试目的?这样做可以安全吗?

我问这个问题是因为我不确定这样做是否合适。当我把这个给我的 friend 看时,他说这样做“不好”。因此,我不确定。

最佳答案

这是一个非常常用和有用的技巧。但最好不要在源代码中包含#define DEBUG。您可以改为在编译命令行中定义它。 g++ -DDEBUG -c file.cpp 将编译代码,就像定义了 DEBUG 一样。

如果您使用的是 Makefile,您可以将其添加到 CPPFLAGS(C 预处理器标志)变量:CPPFLAGS=-DDEBUG

如果您使用的是 IDE,请尝试在项目设置中找到 C 预处理器标志。

关于c++ - 可以做 "#ifdef DEBUG( ... ) __VA_ARGS__"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15694662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com