Writing Function Definition in Header Files in C++

Writing function definition in header files in C++

If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same address for every compilation unit:

headera.h:

inline string method() {
return something;
}

Member functions are implicit inline provided they are defined inside their class. The same stuff is true for them true: If they can be put into the header without hassle, you can indeed do so.

Because the code of the function is put into the header and visible, the compiler is able to inline calls to them, that is, putting code of the function directly at the call site (not so much because you put inline before it, but more because the compiler decides that way, though. Putting inline only is a hint to the compiler regarding that). That can result in a performance improvement, because the compiler now sees where arguments match variables local to the function, and where argument doesn't alias each other - and last but not least, function frame allocation isn't needed anymore.

My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?

Yes, that is correct. The function will be defined in every place where you include its header. The compiler will care about putting only one instance of it into the resulting program, by eliminating the others.

How do you define functions in header files?

You should only write your function's prototype in the header file, the body of your function should be written in a .c file.

Do this :

primary_header.h

/* primary_header.h */
#ifndef PRIMARY_HEADER_H
#define PRIMARY_HEADER_H

#include <stdio.h>

/* Forward declare the primary workhorse function */
void primary(void);

/* Also define a helper function */
void helper(void);

#endif /* PRIMARY_HEADER_H */

primary_impl.c

/* primary_impl.c */
#include "primary_header.h"
#include <stdio.h>

/* Define the primary workhorse function */
void primary()
{
/* do the main work */
printf("I'm the primary function, I'm doin' work.\n");

/* also get some help from the helper function */
helper();
}

void helper()
{
printf("I'm a helper function and I helped!\n");
}

Edit: change _PRIMARY_HEADER_H to PRIMARY_HEADER_H. As @Jonathan Leffler and @Pablo said, underscore names are reserved identifiers

Functions in C Headers?

No, just putting the .c with the .h and including it in your code doesn't magically carry over the definition of the functions too.

You need to compile the foo.c separately into an object file (in case of Linux, it is a .o file). For example using the command -

gcc -c foo.c -o foo.o

Now this foo.o needs to be linked to your actual program. This can be done by simply passing the object file while compiling as

gcc test.c foo.o -o test.out

If you do not link the foo.o with your program, your linker won't be able to find the implementations for the functions defined in it and will throw a linker error as -

Undefined reference to function foo_function.

Is it a good practice to define C++ functions inside header files?

If you want to use a function in multiple source files (or rather, translation units), then you place a function declaration (i.e. a function prototype) in the header file, and the definition in one source file.

Then when you build, you first compile the source files to object files, and then you link the object files into the final executable.


Example code:

  • Header file

      #ifndef FUNCTIONS_H_INCLUDED
    #define FUNCTIONS_H_INCLUDED

    int add(int a, int b); // Function prototype, its declaration

    #endif
  • First source file

      #include "functions.h"

    // Function definition
    int add(int a, int b)
    {
    return a + b;
    }
  • Second source file

      #include <iostream>
    #include "functions.h"

    int main()
    {
    std::cout << "add(1, 2) = " << add(1, 2) << '\n';
    }

How you build it depends very much on your environment. If you are using an IDE (like Visual Studio, Eclipse, Xcode etc.) then you put all files into the project in the correct places.

If you are building from the command line in, for example, Linux or OSX, then you do:

$ g++ -c file1.cpp
$ g++ -c file2.cpp
$ g++ file1.o file2.o -o my_program

The flag -c tells the compiler to generate an object file, and name it the same as the source file but with a .o suffix. The last command links the two object files together to form the final executable, and names it my_program (that's what the -o option does, tells the name of the output file).

Understanding a function definition in a header file

As you have already said, those are not functions but rather macros. You can read about macros in the gcc manual.

A macro is a fragment of code which has been given a name. Whenever
the name is used, it is replaced by the contents of the macro.

That's the summary. There's a lot more detail to it than that. But for starters you can think of macros as code replacement rules. Macros are expanded by the preprocessor before the compiler does it's job.

A simple example:

#define MY_PRINT_MACRO(string1, string2) printf("%s %s\n", string1, string2)

MY_PRINT_MACRO("hello", "world");

The preprocessor will change the second line to be:

printf("%s %s\n", "hello", "world");

And that is exactly what the compiler will see (it does not see MY_PRINT_MACRO at all).

Is it better to keep functions in header files or source files

Header files should not contain any code or data definitions.

In header files:

  1. Function prototypes
  2. Types declarations (typedefs, structs, unions etc)
  3. extern objects declarations
  4. Macro definitions

and as an exception


  1. static inline functions definitions.

All other code or object definitions should be in the .c source files.



Related Topics



Leave a reply



Submit