Is it possible to use GCC to compile one section of a code file with specific compiler flags?(可以使用GCC来编译带有特定编译器标志的代码文件的一段吗?)
问题描述
可以使用GCC编译带有特定编译器标志的代码文件的一段吗?例如,假设我有一些正在测试的函数。我希望这些函数严格遵守标准,所以我想用--Pedtic标志来编译它们。但是,执行测试的代码在编译时会发出很多警告。有没有办法只编译那些特定的函数,用--Pedtic?
或者,假设我有一个精心编写但极其昂贵的函数,它需要尽可能快地运行。如何才能只用-Ofast编译该函数(以及其他几个函数),而用-O2或-03编译程序的其余部分?
推荐答案
实际上有使用#pragma optimize
语句,或使用__attribute__((optimize("-O3")))
所有优化选项都可以找到here。
一个简单的例子是:
#include <stdio.h>
// Using attribute
__attribute__((optimize("-O3"))) void fast_function_attribute()
{
printf("Now calling a slow function, compiled with -O3 flags.
");
}
__attribute__((optimize("-O1"))) void slow_function_attribute()
{
printf("Now calling a slow function, compiled with -O1 flags.
");
}
// Using #pragma
#pragma GCC push_options
#pragma GCC optimize ("-O3")
void fast_function_pragma()
{
printf("This will be another fast routine.
");
}
#pragma GCC pop_options
#pragma GCC push_options
#pragma GCC optimize ("-O1")
void slow_function_pragma()
{
printf("This will be another slow routine.
");
}
#pragma GCC pop_options
int main(void)
{
fast_function_attribute();
slow_function_attribute();
fast_function_pragma();
slow_function_pragma();
}
如果您使用的是不同的编译器,我强烈建议您使用宏来包装它们(或者使用杂注语句而不是__attribute__
以避免任何编译器警告。
这篇关于可以使用GCC来编译带有特定编译器标志的代码文件的一段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以使用GCC来编译带有特定编译器标志的代码文件的一段吗?


- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- GDB 不显示函数名 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01