c++ define function in header

// In header file (Example.h)

#ifndef EXAMPLE_H
#define EXAMPLE_H

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

#endif
// In source file (Example.cpp)

#include "Example.h"

// Function definition
int add(int a, int b) {
    return a + b;
}

Explanation:

  1. // In header file (Example.h): This comment denotes the start of the header file Example.h.

  2. #ifndef EXAMPLE_H: This is an include guard that checks if the header file Example.h has not been defined previously. If it hasn't, it proceeds with the following code.

  3. #define EXAMPLE_H: This line defines the EXAMPLE_H macro, ensuring that if it hasn't been defined before, it gets defined now.

  4. int add(int a, int b);: This line is a function declaration for the add function, specifying its return type (int) and parameters (int a, int b). It tells the compiler that there exists a function named add which takes two int arguments but doesn’t provide its definition.

  5. #endif: This marks the end of the conditional compilation directive started by #ifndef. If EXAMPLE_H was not defined previously, it concludes its definition here.

  6. // In source file (Example.cpp): This comment denotes the beginning of the source file Example.cpp.

  7. #include "Example.h": This line includes the contents of the Example.h header file into the current source file, allowing the functions and declarations in Example.h to be used here.

  8. int add(int a, int b) { return a + b; }: This is the definition of the add function. It defines the functionality of the previously declared add function. In this case, it takes two int arguments a and b and returns their sum.

This structure separates the declaration of functions (in the header file) from their definitions (in the source file), allowing for better code organization and reusability.