Is it possible to use GCC to compile one section of a code file with specific compiler flags? For example, suppose I had some functions I was testing. I want those functions to strictly adhere to standards compliance, so I want to compile them with the --pedantic flag. But the code to do the testing issues a lot of warnings on compilation. Is there any way to compile just those specific functions with --pedantic?
Alternatively, suppose I have a carefully written but extremely expensive function that needs to run as fast as possible. How could I compile just that function (and a few others) with -Ofast, and compile the rest of the program with -O2 or -O3?
There is, actually, using #pragma optimize
statements, or using __attribute__((optimize("-O3")))
All the optimize options can be found here.
A simple example would be:
#include <stdio.h>
// Using attribute
__attribute__((optimize("-O3"))) void fast_function_attribute()
{
printf("Now calling a slow function, compiled with -O3 flags.\n");
}
__attribute__((optimize("-O1"))) void slow_function_attribute()
{
printf("Now calling a slow function, compiled with -O1 flags.\n");
}
// Using #pragma
#pragma GCC push_options
#pragma GCC optimize ("-O3")
void fast_function_pragma()
{
printf("This will be another fast routine.\n");
}
#pragma GCC pop_options
#pragma GCC push_options
#pragma GCC optimize ("-O1")
void slow_function_pragma()
{
printf("This will be another slow routine.\n");
}
#pragma GCC pop_options
int main(void)
{
fast_function_attribute();
slow_function_attribute();
fast_function_pragma();
slow_function_pragma();
}
If you are using different compilers, I would highly recommend wrapping them with macros (or using pragma statements rather than __attribute__
to avoid any compiler warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With