-->

Defining preprocessor symbols for CLion analyzer

2020-08-10 06:10发布

问题:

In my project there's a file enclosed in an ifdef preprocessor directive

#ifdef SOME_SYMBOL
... entire file ...
#endif

SOME_SYMBOL is defined by another file that's compiled before this one, and the code works as expected, but the static analyzer isn't aware of this symbol and so it treats SOME_SYMBOL is undefined. The entire file has no syntax highlighting and some of the analysis is just skipped (e.g. syntax error highlighting).

Is there a way to tell the analyzer to treat this symbol as defined without defining it in CMakeLists.txt?

I don't have the option of defining SOME_SYMBOL in CMakeLists.txt since the project depends on it being undefined in some compilation paths (changing this would be near impossible).

Update:
Seems like this is currently an open issue with JetBrains. See Issue CPP-2286

回答1:

Clion now has a macro which you can use to detect the IDE: https://youtrack.jetbrains.com/issue/CPP-1296#comment=27-1846360

#ifdef __JETBRAINS_IDE__
    // Stuff that only clion will see goes here
#endif

This allows you to put in defines to make clion render your code properly in cases where it can't be clever enough to figure it out.

The __JETBRAINS_IDE__ macro's value is a version string for the IDE. Specific versions of the macro exist for different Jetbrains IDEs: __CLION_IDE__, __STUDIO_IDE__ (for Android Studio), and __APPCODE_IDE__ (for AppCode).

Yay!

Note: At time of writing, this is only available in the latest CLion EAP.



回答2:

To get syntax highlighting: Go to Settings ⇒ Editor ⇒ Colors&Fonts ⇒ C/C++ and remove all ticks for 'Conditionally non-compiled code'. This way all code will show up with the usual highlighting.



回答3:

The task has no solution for common case. But! You can find the target and related resolve context, where SOME_SYMBOL is defined.

...in the status bar you can find the Resolve Context chooser for switching between the Debug, Release, RelWithDebInfo and MinSizeRel contexts to resolve your code in the IDE with the desired definitions.