Search code examples
cvisual-studio-codeintellisense

Usage of ifdef statements for C-Code in VSCode


There are several #ifdef statements in a C-Project. All these #ifdefs are defined in a file named as .cproject. The 'Eclipse' IDE uses this .cproject file and highlights the code under #ifdef that is not being used.

This is not happening in VSCODE. I noticed that although certain #ifdef are true and code under that is being used in a project, the VSCODE shows them as not being used (Display them lightly).

I want to know if there is a way to make sure the VSCODE displays/highlights the correct #ifdef parameter that is used in C-Project.

The .cproject file is an .xml file and all the #ifdefs that are used in a project are defined in that. Can I use that file in some manner in VSCODE or is there any other way to do it?


Solution

  • *** This is assuming you are using VSCode C/C++ Extension from Microsoft

    You can define symbols that are being checked by #ifdef directives in your .vscode/c_cpp_properties.json file (in the project directory), also accessible via > C/C++: Edit Configurations command.

    The structure of the file is like this:

    {
        "configurations": [
            {
                "name": "Linux",
                "includePath": [
                    "${workspaceFolder}/**"
                ],
                "defines": [
                    "FOO"
                ],
                "cppStandard": "gnu++14",
                "intelliSenseMode": "linux-gcc-x64"
            },
            {
                "name": "WSL",
                "includePath": [
                    "${workspaceFolder}/**"
                ],
                "defines": [
                    "BAR"
                ],
                "cppStandard": "gnu++14",
                "intelliSenseMode": "linux-gcc-x64"
            }
        ],
        "version": 4
    }
    

    And the symbols you want to define are under the "defines" array of strings (FOO and BAR for the two configurations above)..

    Keep in mind that these definitions only affect the IntelliSense behavior, it does not define these symbols for the compiler/preprocessor! If you want to define these for the compiler/preprocessor, you will need to do it elsewhere.

    Here is the full documentation for your reference:
    https://code.visualstudio.com/docs/cpp/c-cpp-properties-schema-reference

    and the specific excerpt:

    defines - A list of preprocessor definitions for the IntelliSense engine to use while parsing files. Optionally, use = to set a value, for example VERSION=1.