Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 934
Alecto Irene Perez Avatar asked Mar 09 '23 16:03

Alecto Irene Perez


1 Answers

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.

like image 134
Alexander Huszagh Avatar answered Apr 26 '23 23:04

Alexander Huszagh