16

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?

  • Have you tried simply running cmake again with the build type set to DEBUG? e.g. (from the Build directory) cmake -DCMAKE_BUILD_TYPE=DEBUG .. – steeldriver Feb 28 '15 at 23:01
  • 1
    Why wasn't this posted on Stack Overflow? – Peter Mortensen Aug 30 '18 at 13:49
9

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.

7

Or at invocation time:

cmake -DCMAKE_BUILD_TYPE=DEBUG \
      -DCMAKE_C_FLAGS_DEBUG="-g -O0" \
      -DCMAKE_CXX_FLAGS_DEBUG="-g -O0"

and then confirm with:

make VERBOSE=1

to show the GCC build commands as explained at: https://stackoverflow.com/questions/5820303/how-do-i-force-make-gcc-to-show-me-the-commands

Tested on Ubuntu 17.04, CMake 3.7.2.

4

Add this to CMakeLists.txt (the one in the project source directory; don't touch anything in the build directory):

SET(CMAKE_CXX_FLAGS_DEBUG "-O0")
SET(CMAKE_C_FLAGS_DEBUG "-O0")

and then

$ cmake -DCMAKE_BUILD_TYPE=Debug

will work. Alternatively just add this to CMakeLists.txt:

SET(CMAKE_CXX_FLAGS "-O0")
SET(CMAKE_C_FLAGS "-O0")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.