# 15.4 复制编译标志

现在，让我们尝试调整编译器标志来进行引用构建。

## 定义编译器标志

目前为止，我们还没有定义任何自定义编译器标志，参考Autotools构建中，代码是使用的编译标志有`-g -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2`，这些标示都是GNU C编译器可以识别的。

我们的第一个定义如下:

```
if(CMAKE_C_COMPILER_ID MATCHES GNU)
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2")
endif()
```

并且，在生成源文件之前，我们将把这段代码放在`src/CMakeLists.txt`的顶部(因为`pathdef.c`有使用到`${CMAKE_C_FLAGS}`):

```
# <- we will define flags right here
include(autogenerate.cmake)
generate_config_h()
generate_pathdef_c()
generate_osdef_h()
```

编译器标志定义的一个小修改是将`-O2`定义为Release配置标志，并关闭Debug的配置:

```
if(CMAKE_C_COMPILER_ID MATCHES GNU)
  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -U_FORTIFY_SOURCE
  -D_FORTIFY_SOURCE=1")
  set(CMAKE_C_FLAGS_RELEASE "-O2")
  set(CMAKE_C_FLAGS_DEBUG "-O0")
endif()
```

请使用`make VERBOSE=1`验证，构建是否使用了预期的标志。

## 编译器标志的作用域

在这个特殊的示例项目中，所有源文件都使用相同的编译标志。对于其他项目，我们可能不希望像上面那样全局定义编译标志，而是使用`target_compile_options`为每个目标分别定义编译标志。这样做的好处是更灵活、范围更小。在我们的例子中，这能减少不必要的代码复制。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chenxiaowei.gitbook.io/cmake-cookbook/15.0-chinese/15.4-chinese.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
