Run C program in debug mode (without debugger)

If I want my program to be able to run in debug mode, is it a good idea to make it accept a flag such as -D=DEBUG when I run the program? I currently have a DEBUG variable in a .h file but that I can’t change after I compile.

#define DEBUG false

I’d like to be able to run my program both in debug mode and “stable” mode. Is getops a good option for doing this since I already use getops for accepting the args ./a.out --help and ./a.out --version ?


You are better off to make a clear distinction between “compile time debug” mode (which is what you control by #define DEBUG), and specific “debug features” which should be available even when you compile with #define DEBUG false, and could be enabled or disabled at run time. Better call the latter differently, name the features (like “logging mode”, “validating mode” etc.), and provide different command line flags for them.

That gives you the opportunity to enable these features even when you deployed the program into production environment, where you might not be able to use a debugger.

The whole point of compiling in “debug mode” is that it includes debug symbols in the executable to enable the use of a debugger, at the cost of foregoing some performance optimizations that aren’t possible with debug symbols. If you don’t plan on running that executable in a debugger, then “being in debug mode” doesn’t gain you anything.

It’s likely that you’re conflating debug mode (which is something you do at compile time) with other features that actually are useful to have in a release binary, such as a -v flag (passed by the user at runtime) for increased verbosity in command line tools, or a diagnostic mode in video games (triggered by the user during execution) to help players identify lag sources on their server. Whether these should be command line arguments or something else depends on the application.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *