The inline
keyword in C++ helps manage the One Definition Rule (ODR) by allowing functions and variables to be defined in header files without causing multiple definition errors.
The ODR states that there should be only one definition of any variable, function, class, or type in the entire program. However, multiple declarations are allowed.
inline
The inline
keyword tells the compiler that it can include the function or variable definition in multiple translation units but treat it as a single definition.
Without inline
, defining a function in a header file would cause multiple definitions:
// utils.h
#pragma once
void PrintHello() {
std::cout << "Hello\n";
}
Including utils.h
in multiple source files causes a linker error:
main.obj : error LNK2005: "void PrintHello(void)" already defined in other.obj
Using inline
solves this:
// utils.h
#pragma once
inline void PrintHello() {
std::cout << "Hello\n";
}
Now, PrintHello()
can be included in multiple files without causing multiple definitions.
For variables, the inline
keyword is similarly useful. Without inline
, defining a variable in a header file causes errors:
// globals.h
#pragma once
int GlobalVar{42};
Using inline
allows it to be defined in multiple files:
// globals.h
#pragma once
inline int GlobalVar{42};
Here’s a complete example:
// globals.h
#pragma once
inline int GlobalVar{42};
inline void PrintGlobalVar() {
std::cout << "GlobalVar: " << GlobalVar << '\n';
}
// main.cpp
#include <iostream>
#include "globals.h"
int main() {
PrintGlobalVar();
}
// other.cpp
#include "globals.h"
// Additional code can use GlobalVar
// and PrintGlobalVar here
g++ main.cpp other.cpp -o myProgram
./myProgram
GlobalVar: 42
inline
keyword ensures the compiler treats multiple instances of a function or variable definition as a single definition.Using the inline
keyword effectively helps manage the ODR, allowing for more flexible and modular code organization in C++Â projects.
Answers to questions are automatically generated and may not have been reviewed.
A deeper look at the C++ linker and how it interacts with our variables and functions. We also cover how we can change those interactions, using the extern
and inline
keywords