Issue
Using Visual Studio Code 1.39.2 on Ubuntu 18.04. My C++ program has tasks for generating a Makefile with Cmake using the command cmake -G 'Unix Makefiles' -DCMAKE_BUILD_TYPE=Debug ..
. There is an equivalent Release
version.
Thereafter, a make
task is run which correctly builds a DEBUG and RELEASE version in ./PROJECT/build/Debug
or ./PROJECT/build/Release
folders.
The problem is that Visual Studio Code does not understand any Debug
or _DEBUG
symbols, so code like the following does not work as expected:
#ifdef _DEBUG // or #ifdef Debug
cout << "Debug build\n";
#else
cout << "Release build\n";
#endif
When the application is run, only Release build
is printed, never Debug build
. Moreover, in the Visual Studio Code editor, the Debug build
line is greyed out.
Manually defining the symbols with #define DEBUG
is an option, but will require manually editing the file every time the build type is changed.
How do you get Visual Studio Code to define and understand the correct symbols based on the selected build task? Or is there some clever way to get Code to "look into" the generated CMake/make files (such as CMakeCache.txt, cmake_install.cmake, Makefile)?
Solution
Note: This solution will resolve the issue of symbols not being understood during compilation. However, the problem of the Visual Studio editor not understanding the _DEBUG
or NDEBUG
symbols for presentation remains an issue.
In comments to the question, this question was suggested as a duplicate. There is some overlap, but that question refers to the Eclipse IDE and uses obsolete CMake commands. But it did gives some clues and after digging into the CMake documentation, allows the problem to be resolved with these changes to CMakeLists.txt
:
Step 1 - If required, set the CMake build type explicitly
Near the top of CMakeLists.txt
, add the following:
if (CMAKE_BUILD_TYPE STREQUAL "")
# Build type is not set eg. command was "cmake .."
message(STATUS " Diag: Build type was unspecified, set to Release")
set(CMAKE_BUILD_TYPE Release)
else ()
message(STATUS " Diag: Build type specified as '${CMAKE_BUILD_TYPE}'")
endif ()
Step 2 - Define "_DEBUG" and other symbols
After the code from step 1 add the following:
if (${CMAKE_BUILD_TYPE} STREQUAL Debug)
set_directory_properties(PROPERTIES COMPILE_DEFINITIONS "_DEBUG")
else ()
set_directory_properties(PROPERTIES COMPILE_DEFINITIONS "NDEBUG")
endif ()
Now call CMake in one of the following three ways from some build
folder. This can either be from the command-line or as a task inside Visual Studio Code, then make
the final binary:
- cmake ..
- cmake -G 'Unix Makefiles' -DCMAKE_BUILD_TYPE=Release ..
Release binary and Release build
is displayed
- cmake -G 'Unix Makefiles' -DCMAKE_BUILD_TYPE=Debug ..
Debug binary and Debug build
is displayed
Answered By - AlainD Answer Checked By - Candace Johnson (WPSolving Volunteer)