The role of #ifdef and #ifndef

Text inside an ifdef/endif or ifndef/endif pair will be left in or removed by the pre-processor depending on the condition. ifdef means “if the following is defined” while ifndef means “if the following is not defined”. So: #define one 0 #ifdef one printf(“one is defined “); #endif #ifndef one printf(“one is not defined “); #endif … Read more

#ifdef vs #if – which is better/safer as a method for enabling/disabling compilation of particular sections of code?

My initial reaction was #ifdef, of course, but I think #if actually has some significant advantages for this – here’s why: First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example – Often, I want longer timeouts when debug is enabled, so using #if, I can write this DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000); … instead … Read more

Macros to create strings in C

In C, string literals are concatenated automatically. For example, const char * s1 = “foo” “bar”; const char * s2 = “foobar”; s1 and s2 are the same string. So, for your problem, the answer (without token pasting) is #ifdef __TESTING #define IV_DOMAIN “example.org” #elif __LIVE_TESTING #define IV_DOMAIN “test.example.com” #else #define IV_DOMAIN “example.com” #endif #define … Read more

How to view C preprocessor output?

gcc -E file.c or g++ -E file.cpp will do this for you. The -E switch forces the compiler to stop after the preprocessing phase, spitting all it’s got at the moment to standard output. Note: Surely you must have some #include directives. The included files get preprocessed, too, so you might get lots of output. … Read more

offsetof at compile time

The offsetof() macro is a compile-time construct. There is no standard-compliant way to define it, but every compiler must have some way of doing it. One example would be: #define offsetof( type, member ) ( (size_t) &( ( (type *) 0 )->member ) ) While not being a compile-time construct technically (see comments by user … Read more