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:
// In header file (Example.h)
: This comment denotes the start of the header fileExample.h
.#ifndef EXAMPLE_H
: This is an include guard that checks if the header fileExample.h
has not been defined previously. If it hasn't, it proceeds with the following code.#define EXAMPLE_H
: This line defines theEXAMPLE_H
macro, ensuring that if it hasn't been defined before, it gets defined now.int add(int a, int b);
: This line is a function declaration for theadd
function, specifying its return type (int
) and parameters (int a, int b
). It tells the compiler that there exists a function namedadd
which takes twoint
arguments but doesn’t provide its definition.#endif
: This marks the end of the conditional compilation directive started by#ifndef
. IfEXAMPLE_H
was not defined previously, it concludes its definition here.// In source file (Example.cpp)
: This comment denotes the beginning of the source fileExample.cpp
.#include "Example.h"
: This line includes the contents of theExample.h
header file into the current source file, allowing the functions and declarations inExample.h
to be used here.int add(int a, int b) { return a + b; }
: This is the definition of theadd
function. It defines the functionality of the previously declaredadd
function. In this case, it takes twoint
argumentsa
andb
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.