cmake中添加 -g编译选项

    科技2025-07-13  17

    在cmake 3.12之前,添加编译选项可以如下方式添加

    add_definitions("-Wall -g")

    添加了之后,就相当于在编译的时候加上了 -Wall -g选项

    #没加之前 gcc -c main.c -o test #添加之后,相当于 gcc -g -Wall -c main.c -o test

    书中给出的示例如下:

    add_definitions(-DSomeSymbol /DFoo=Value ...) remove_definitions(-DSomeSymbol /DFoo=Value ...)

    但是到cmake 3.12之后,最好使用编译选项专用的添加方式:

    add_compile_definitions(SomeSymbol Foo=Value ...)

    通过指令

    $ cmake --version cmake version 3.18.4 CMake suite maintained and supported by Kitware (kitware.com/cmake).

    查看自己的cmake版本,若是在3.12之后的版本最好使用add_compile_definitions函数,要是3.12之前的版本,只能使用add_definitions或者直接设置变量的方式进行

    这里给出一个CMakeLists.txt的小例子,这个小例子是在学习设计模式的时候编写的一个用于编写多个可执行小demo的cmake文件,全部工程包括设计模式源码见: 23种设计模式cpp实现工程源码地址

    # 针对cmake版本的要求 # cmake version 3.18.3 cmake_minimum_required(VERSION 3.5) project(cppDesignPatterns) add_definitions("-Wall -g") # 开闭原则 add_executable(open_close_principle open_close_principle.cpp) # 依赖颠倒原则 add_executable(reverse_dependencies reverse_dependencies.cpp) # 懒汉式单例模式 add_executable(sluggard_singleton sluggard_singleton.cpp) # 饿汉式单例模式 add_executable(hungry_singleton hungry_singleton.cpp) #target_include_directories( PUBLIC ./../lib)
    Processed: 0.011, SQL: 8