In GCC, many function attributes can be used to give syntax to the compiler for useful optimization/profiling of the code.
Helpful link: https://www.acrc.bris.ac.uk/acrc/RedHat/rhel-gcc-en-4/function-attributes.html
For instance, the typical usage of function attribute would look something like this:
// foo.h
__attribute__((no_instrument_function)) void foo();
// test.c
// gcc -finstrument-functions test.c -o test
#include <stdio.h>
#include "foo.h"
void foo() { printf("Foo\n"); }
int main() { foo(); return 0; }
Compiling the above code will insert __cyg_profile_func_enter
and __cyg_profile_func_exit
only in main
function, and avoid inserting them in foo
.
Now I wonder whether it is possible to declare a function attribute(s) of target function(s) in a separate file.
For instance, if I have foo.h
and bar.h
without the attribute, is there a way to have a single file that gives attributes to both foo
and bar
functions?
For instance, I tried to solve this question by doing something like this (incorrect solution):
// attributes.c
void foo() __attribute__((no_instrument_function));
void bar() __attribute__((no_instrument_function));
// bar.h
void bar();
// foo.h
void foo();
// test.c
// gcc -finstrument-functions attributes.c test.c -o test
#include <stdio.h>
#include "foo.h"
#include "bar.h"
void foo() { printf("Foo\n"); }
void bar() { printf("Bar\n"); }
int main() { foo(); return 0; }
The use case or the reason I am trying to solve this problem is that, unlike these microbenchmarks, I am trying to apply function attributes to a much larger program with many source/header files. In other words, there are many functions that I wish to declare function attributes for many functions that are spread across different files, and I think it is a lot easier to create a single file and insert that into the Makefile
.
I think I could create a script to scan through the folder and add the attributes automatically (using regex) or manually by inserting the code. Still, I am exploring whether there is a cleaner solution to this question. Thank you in advance!
The GCC documentation says āCompatible attribute specifications on distinct declarations of the same function are merged.ā That means you can declare an attribute in one declaration (such as the first one in a translation unit) and omit it in a later declaration (including the function definition), and the attribute will be merged into the later declaration.
However, you cannot merely put them into a separate source code file, as you do with attribute.c
, and then compile them separately from the other source code. The compiler must see the attribute when it is compiling the source code that is affected by it. You could put them in a file named attribute.h
and then include attribute.h
in your other header files.