String comparison in preprocessor conditions in C

梦想与她 提交于 2020-01-15 06:52:21

问题


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?


回答1:


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 


来源:https://stackoverflow.com/questions/18278868/string-comparison-in-preprocessor-conditions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!