2

What is the purpose of the #ifdef below? And why does it allow me to step through my program when debugging it (active solution configuration = debug) but not when the active solution configuration = release or when building the solution and the active solution configuration = release?

#ifdef RUN
int main(int argc, char* argv[])
{
   Some functions

}
#endif

I am working with someone else's legacy code, and I know I can just remove it and it will behave normally, but I want to understand why the previous coder placed these preprocessor directives here in the first place.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
traggatmot
  • 1,423
  • 5
  • 26
  • 51
  • Most likely there is a preprocessor directive in Visual Studio configuration manager that defines `RUN` in debug but not release, for reasons explained in the answers below. Check this answer for how to setup preprocessor directives: http://stackoverflow.com/questions/4045897/visual-studio-incorrectly-marking-inactive-code-blocks-when-using-ifdef – amdn Oct 29 '14 at 21:27

2 Answers2

2

Recall that in a linked C program there can only be one main() function.

Therefore if this is intended to be used as library code, main needs to be turned off (removed in precompiling).

If it is to be run standalone, main should be left in.

It may be used for the file's test cases. It may also become a standalone server, where the library code will basically still run as library code, only over IPC rather than linked in directly.

To me, this is bad practice and reflects a problem in the build, where the C programmer was more competent than the build engineer, who couldn't figure out how to properly separate the components. Refactoring is needed.

I would consider the following before removing:

  • are they test cases? (if yes refactor into proper test code)
  • is RUN ever actually turned on anywhere in the system? if yes where and why; if not safer to remove likely
  • consider #ifdef RUN #error as a way to break the build if it surprises you to learn the flag is sometimes defined, or #ifndef for vice versa. Note I said "consider"; please understand the implications of breaking the build first.
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • RUN is never actually turned on in the system anywhere. It is not a "test" case, tho those do exist elsewhere in the code. – traggatmot Oct 29 '14 at 21:48
  • 1
    @traggatmot probably worth a best effort at what you think the code does before removing. Source control with comments, right? – djechlin Oct 29 '14 at 21:59
1

For example when just a library needs to be build with any main function which typically does not require any main function. The main function is used to test something.

sfrehse
  • 1,062
  • 9
  • 22