Skip to content

Is it possible to use GCC to compile one section of a code file with specific compiler flags?

An answer to this question on Stack Overflow.

Question

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?

Answer

Yes.

#include <iostream>
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wpedantic"
#pragma GCC push_options
#pragma GCC optimize ("O0")
void bob(){
  std::cerr<<"Sandwich maker!"<<std::endl;
}
#pragma GCC diagnostic pop
#pragma GCC pop_options
int main(){
  bob();
}

The push_options and diagnostic push saves the optimization and diagnostic flags, respectively, prior to altering those to pedantic and O0 (or O1, O2, O3, Os, Og). The pop pragmas restore the original settings.

More details on optimization pragmas are here and details on diagnostic pragmas are here.