Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set CFLAGS and CXXFLAGS options using CMake

Tags:

cmake

cflags

I just want to debug some code running on Linux and I need a debug build (-O0 -ggdb). So I added these things to my CMakeLists.txt:

set(CMAKE_BUILD_TYPE DEBUG) set(CMAKE_C_FLAGS "-O0 -ggdb") set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb") set(CMAKE_C_FLAGS_RELEASE "-O0 -ggdb") set(CMAKE_CXX_FLAGS "-O0 -ggdb") set(CMAKE_CXX_FLAGS_DEBUG "-O0 -ggdb") set(CMAKE_CXX_FLAGS_RELEASE "-O0 -ggdb") 

When I tried to compile I turned verbose on using make VERBOSE=1 And I observed the output, like this

... /usr/bin/c++ -D_BSD_SOURCE **-O0 -ggdb** -Wnon-virtual-dtor  -Wno-long-long -ansi -Wundef -Wcast-align -Wchar-subscripts -Wall -W  -Wpointer-arith -Wformat-security -fno-exceptions -DQT_NO_EXCEPTIONS  -fno-check-new -fno-common -Woverloaded-virtual -fno-threadsafe-statics  -fvisibility=hidden -fvisibility-inlines-hidden **-g -O2**  -fno-reorder-blocks -fno-schedule-insns -fno-inline ... 

Apparently the code is compiled with "-g -O2" and this is not what I want. How can I force it to use "-O0 -ggdb" only?

like image 531
majie Avatar asked Apr 10 '12 09:04

majie


People also ask

Does CMake use Cflags?

This is a CMake Environment Variable. Its initial value is taken from the calling process environment. Default compilation flags to be used when compiling C files.

How do you set a variable in CMakeLists txt?

You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake .

What is Cflags in Makefile?

CFLAGS and CXXFLAGS are either the name of environment variables or of Makefile variables that can be set to specify additional switches to be passed to a compiler in the process of building computer software.


2 Answers

You need to set the flags after the project command in your CMakeLists.txt.

Also, if you're calling include(${QT_USE_FILE}) or add_definitions(${QT_DEFINITIONS}), you should include these set commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb") 
like image 111
Fraser Avatar answered Sep 21 '22 00:09

Fraser


The easiest solution working fine for me is this:

export CFLAGS=-ggdb export CXXFLAGS=-ggdb 

CMake will append them to all configurations' flags. Just make sure to clear CMake cache.

like image 40
Virus_7 Avatar answered Sep 20 '22 00:09

Virus_7