Menu

Preprocessor error on preprocessor-if in macro

2025-05-06
2025-05-06
  • Oliver Parczyk

    Oliver Parczyk - 2025-05-06

    While setting up cppcheck for a larger codebase (and working around my other problems) I've uncovered another issue, this time concering some... gymnastics using the preprocessor. It's not as contrived but I can't share the original.

    I've condensed it into this example:

    #define ADD_INT(x, y) x+y
    
    int main() {
        return ADD_INT(1,
    #if 1
        5
    #else
        6
    #endif
         );
    }
    

    cppcheck (both latest master and last release) give the following* error:

    $ cppcheck preprocessorError.c 
    Checking preprocessorError.c ...
    preprocessorError.c:5:0: error: failed to expand 'ADD_INT', it is invalid to use a preprocessor directive as macro parameter [preprocessorErrorDirective]
    #if 1
    ^
    

    *: Perhaps interestingly, the build from master gives the error twice:

    $ cppcheck preprocessorError.c 
    Checking preprocessorError.c ...
    preprocessorError.c:5:0: error: failed to expand 'ADD_INT', it is invalid to use a preprocessor directive as macro parameter [preprocessorErrorDirective]
    #if 1
    ^
    preprocessorError.c:5:1: error: failed to expand 'ADD_INT', it is invalid to use a preprocessor directive as macro parameter [preprocessorErrorDirective]
    #if 1
    ^
    

    Note that replacing #if 1 with #ifdef NOT_DEFINED doesn't change this behaviour.

    both clang and gcc build this code just fine, their preprocessor output behaves as expected (I've removed a few blank lines):

    $ cpp preprocessorError.c 
    # 0 "preprocessorError.c"
    # 0 "<built-in>"
    # 0 "<command-line>"
    # 1 "/usr/include/stdc-predef.h" 1 3 4
    # 0 "<command-line>" 2
    # 1 "preprocessorError.c"
    
    int main() {
     return 1 +5
       ;
    }
    
     
  • CHR

    CHR - 2025-05-06
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.