Question

I am developing in C using gcc in Linux.

I am organizing my small functions in .H and .C files in the following way

      // .H file
      extern int my_function( int val );

      // .C file
      inline int my_function( int val ){
          // my job..very short!
      }

These functions are small so they are very good candidates to be inlined but I don't know if they will be for sure.

I have doubt about the way I cam organizing my file and I was thinking that probably it would be better to have all my functions inlined directly into the .h file without .C file. Can you help me a bit in clarifying my doubt?

Was it helpful?

Solution

First of all, note that you can tell gcc to try and inline small functions into their callers by adding the -finline-functions option.

If you have any doubt that your function will actually be inlined, you can ask gcc to warn you about uninlinable function, by using -Winline

Here, as your functions are declared both extern and inline, they will be inlined as the inline definition will only be used for inlining. In this particular situation the function will not be compiled on its own at all.

Read http://gcc.gnu.org/onlinedocs/gcc/Inline.html for further details.

OTHER TIPS

No matter how small your function is, the choice is compiler's whether or not to inline it.

So even if you have very few number of functions and you inline them all in your code, there's still no guarantee that all will be inlined by the compiler.

You can find some useful inshgts on inlining here.

First, the compiler must be able to see the definition of a function in order to inline it. Hence, you must place the definition in the header file. (Here, I'm assuming your application consists of more than one source file). Note: Some development environments support multi-file compilation, in which case this remark does not apply.

Secondly, the semantics of inline C99 is a bit confusing if you are accustomed C++ (where things "just work"). In C99, you must single out a single source file (not header file) which own the function -- in case the function is not inlined in some source file, there must exist exactly one explicit definition of the function. This is done by specifying the function using the extern keyword. (This is a deviation from the traditional interpretation of extern, that it was used for declarations only).

For example:

  // .h file
  inline int my_function( int val )
  {
      // my job..very short!
  }

  // In ONE .c file
  extern int my_function( int val );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top