Search code examples
c++macroscompiler-flags

How to disable intelllisense errors in vscode when using macros defined with -D flag?


I have a CMake file which defines PROJECT_PATH macro for my project with the -D flag. I want to be able to use that macro in code to access a file relative to that path, like this:

auto file = open_file(std::string(PROJECT_PATH) + 'path/to/the/file.txt');

Is there any way to disable the intellisense error messages only for that particular macro?

Edit: I have found a dirty solution which works for now:

in the .vscode/settings.json I added:

    "C_Cpp.default.defines": [
        "${default}",
        "PROJECT_DIR=\"\"" // dirty hack to disable intellisense errors 
    ]

Solution

  • To let IntelliSense know about your macros, you must create the file c_cpp_properties.json in your .vscode folder.

    There you can specify your macros in the field "defines". However, this is not perfect because you have to do it twice, once in the build and once here.

    A better approach is to use "compileCommands", where you can set the path to file compile_command.json, where will be placed all macros from the build. CMake automatically generates this file if you turn it on with the CMAKE_EXPORT_COMPILE_COMMANDS definition.

    c_cpp_properties.json

    {
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            // macro defined only for intelisense. It won't be used for build
            "defines": [
                "MY_DEFINE=\"some_text\""
            ],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-gcc-x86",
            // owerwrite inlucdes and defines with values used from build
            "compileCommands": "${workspaceFolder}/build/compile_commands.json",
            "browse": {
                "path": [
                    "${workspaceFolder}/**"
                ]
            }
        }
    ],
    "version": 4
    }
    

    CMakeLists.txt

    cmake_minimum_required(VERSION 3.0.0)
    project(TestArea VERSION 0.1.0)
    
    set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
    
    add_compile_definitions(MY_DEFINE="some/path")
    
    add_executable(TestArea test.cpp)