-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.

2
  • 1
    Does this answer your question? Can the C preprocessor be used to tell if a file exists? Commented Feb 17, 2023 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... Commented Feb 17, 2023 at 10:56

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.