Jonathan Beerhalter
Jonathan Beerhalter

Reputation: 7407

Can I set a C# preprocessor directive from a central file?

I need to add some logging to my app, and it needs to be in release mode, and I need to make sure that the logging code isn't running in production. Therefore I'd like to use a #define and #if to make sure the log statements are removed when I move to production.

Trouble is, I need the logging in multiple files, and it's a pain to put a #define at the top of every file. Is there a way to have a centralized #define? That way I can remove the single #define rather than a #define from all files(which means I'll almost assuredly forget one).

Upvotes: 5

Views: 2383

Answers (5)

Eric Lippert
Eric Lippert

Reputation: 660249

On the command line, use the /define switch. In Visual Studio, choose the "Build" tab from the properties page for the project and fill in the "Conditional Compilation Symbols" section.

Consider also instead of using conditional compilation, to instead make your logging methods conditional methods. That's a more pleasant-looking alternative. That's how Debug.Assert works; it is a conditional method, so if the debug preprocessor symbol is not defined, the compiler simply removes all calls to the method before code generation.

See also my article on the subject:

http://ericlippert.com/2009/09/10/whats-the-difference-between-conditional-compilation-and-the-conditional-attribute/

Upvotes: 9

Benjamin Podszun
Benjamin Podszun

Reputation: 9827

Call the logging everywhere you want.

Define the logging api entry methods with

[Conditional ("DEBUG")]
public void WriteDebugMessage(...)

Build your program in debug mode (which, by default, defines 'DEBUG' in VS). These calls will be part of your assembly.

Build your program in release mode (or - remove the DEBUG symbol from the build definition). These calls are now meaningless no-ops and won't run.

Seems like what you want?

Upvotes: 1

John Saunders
John Saunders

Reputation: 161781

Are you using Visual Studio? In the project Properties page, on the "Build" tab, there's a "Conditional compilation symbols" text box.

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185653

To add to Dave's answer, global conditional compilation symbols can also be specified in Visual.

  1. Right-click on your project and go to Properties
  2. Go to the Build tab

You can specify the symbols that you like (DEBUG is already turned on by default for Debug configurations, so this might actually give you what you want already) for the given configuration, or select "All Configurations" at the top to specify certain symbols for all configurations.

Upvotes: 1

Dave Markle
Dave Markle

Reputation: 97751

Yes, this is typically done in your build file, or the script you use which creates your build. You specify it as command-line arguments to MSBuild.

Upvotes: 1

Related Questions