How to compile without optimizations -O0 using CMake

cmakedebugginggdboptimization

I am using Scientific Linux (SL). I am trying to compile a project that uses a bunch of C++ (.cpp) files.

In the directory user/project/Build, I enter make to compile and link all the .cpp files. I then have to go to user/run/ and then type ./run.sh values.txt

To debug with GDB, I have to go to user/run and then type gdb ../project/Build/bin/Project and to run, I enter run -Project INPUT/inputfile.txt. However, I am trying to print out the value of variable using p variablename.

However, I get the message s1 = <value optimized out>. I have done some research online, and it seems I need to compile without optimizations using -O0 to resolve this. But where do I enter that? In the CMakeLists? If so, which CMakeLists? The one in project/Build or project/src/project?

Best Answer

Chip's answer was helpful, however since the SET line overwrote CMAKE_CXX_FLAGS_DEBUG this removed the -g default which caused my executable to be built without debug info. I needed to make a small additional modification to CMakeLists.txt in the project source directory to get an executable built with debugging info and -O0 optimizations (on cmake version 2.8.12.2).

I added the following to CMakeLists.txt to add -O0 and leave -g enabled:

# Add -O0 to remove optimizations when using gcc
IF(CMAKE_COMPILER_IS_GNUCC)
    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0")
    set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0")
ENDIF(CMAKE_COMPILER_IS_GNUCC)

This adds the -O0 optimization to flags already used for debug by CMake and only is included for GCC builds if you happen to be using a cross platform project.

Related Question