Comparison of strings in preprocessor conditions in C

I am passing a compiler option to a makefile called DPATH

, something like DPATH=/path/to/somefile

. Based on this, I have to write a macro to: -

#if "$(DPATH)"=="/path/to/x"
#error no x allowed
#endif

      

How to compare DPATH

with a string in a conditional preprocessor test?

+2


source to share


1 answer


This cannot be done in the preprocessor. #if

can only evaluate whole expressions without referencing functions or variables. All identifiers that survive expansion of the macro are replaced with zeros, and the string constant triggers an automatic syntax error.

Without knowing more about your problem, I would suggest writing a tiny test program that is compiled and executed at build time, and the Makefile goo will fail to build if the test fails.

#include <stdio.h>
#include <string.h>
int main(void)
{
   if (!strcmp(DPATH, "/path/to/x") || some1 == 3 || some2 == 7 || ...)
   {
       fputs("bogus configuration\n", stderr);
       return 1;
   }
   return 0;
}

      



and then

all : validate_configuration
validate_configuration: config_validator
    if ./config_validator; then touch validate_configuration; else exit 1; fi
config_validator: config_validator.c
    # etc 

      

+3


source







All Articles