Sayan
Sayan

Reputation: 2724

String comparison in preprocessor conditions in C

I am passing a compiler option in makefile called DPATH, which is something like DPATH=/path/to/somefile. Based on this, I have to write a macro such that:-

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

How do I compare DPATH with the string in a preprocessor conditional test?

Upvotes: 2

Views: 2931

Answers (1)

zwol
zwol

Reputation: 140569

It is not possible to do this in the preprocessor. #if can only evaluate integer expressions making no reference to functions or variables. All identifiers that survive macro expansion are replaced by zeroes, and a 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 during the build, and Makefile goo to fail the build if the test doesn't pass.

#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 

Upvotes: 4

Related Questions