Utku Boduroglu Utku Boduroglu - 1 month ago 8
C Question

Preprocessor definitions not working in C

I've been frantically trying to get this following code to work. The preprocessor definitions WIDR and LIDR aren't working and it's giving me the compile error:

projects/elcain.c: In function ‘main’:
projects/elcain.c:17:6: error: ‘WIDR’ undeclared (first use in this function)
if ( WIDR ) {
^
projects/elcain.c:17:6: note: each undeclared identifier is reported only once for each function it appears in
projects/elcain.c:19:13: error: ‘LIDR’ undeclared (first use in this function)
} else if ( LIDR ) {


I don't really have experience with preprocessor macros, or the preprocessor in general, so go easy on me.

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#define WIDR 1
#elif defined _linux_
#define LIDR 1
#endif

int main () {

char* directory = (char*) malloc (1);
if ( WIDR ) {
strcpy(directory, "C:\\TEMP\\");
} else if ( LIDR ) {
strcpy(directory, "~/.temp/");
} else {
*directory = 0x00;
}

printf("%s\n", directory);
return 0;
}

Answer

What you are looking for is something like this:

#include <stdlib.h>

#if defined unix        ||                                                     \
    defined __unix      ||                                                     \
    defined __unix__    ||                                                     \
    defined __linux__   ||                                                     \
    defined __FreeBSD__ ||                                                     \
    defined __CYGWIN__  ||                                                     \
    (defined __APPLE__ && defined __MACH__)
    static const char TMP_DIR[] = "~/.temp/";
#elif defined WIN32   ||                                                       \
      defined _WIN32  ||                                                       \
      defined __WIN32
    static const char TMP_DIR[] = "C:\\TEMP\\";
#else
    #error "Platform not supported"
#endif

int
main(void)
{
    printf("%s\n", TMP_DIR);
    return EXIT_SUCCESS;
}