-3

I wanted to #define some macros based on whether particular directory is present in Linux, I can't use any fopen/directory/stat API's here since they are exposed during compilation phase

Example,

Need to set ---->Someway to check directory existing using C macro, i.e before compilation phase #define RANDOM 100 #else #define RANDOM 200

Need help here.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    Does this answer your question? [Can the C preprocessor be used to tell if a file exists?](https://stackoverflow.com/questions/142877/can-the-c-preprocessor-be-used-to-tell-if-a-file-exists) – Elias Holzmann Feb 17 '23 at 10:56
  • 4
    I am afraid that this is not directly possible. Furthermore, a C program is expected to be built once and then used many times. What if the directory does not exist at build time but later exists at run time? If you really want to go that way, you could look at how automake/autoconf work... – Serge Ballesta Feb 17 '23 at 10:56

2 Answers2

4

You can define a macro from the command line using the -D preprocessor option, in your case:

gcc -o demo demo.c -DRANDOM=$(test -d /path/to/some/dir && echo 100 || echo 200)

You simply read RANDOM from your program:

#include <stdio.h>
 
int main(void) 
{
    printf("%d\n", RANDOM);
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

You can't do this as the preprocessor textually replaces one value with another (more precisely it replaces tokens). It is done before the actual C code compilation.

You need to have variable RANDOM (not macro definition) and assign it with the value runtime.

int RANDOM = 0;
if(directory_exists(directory))
{ 
     RANDOM = 200
}
else
{ 
     RANDOM = 500
}

and use it later in your code.

0___________
  • 60,014
  • 4
  • 34
  • 74