Using inline
variables, introduced in C++17, offers several advantages over traditional methods to avoid multiple definitions.
These variables are particularly useful when you need a global variable to be accessible across multiple translation units without causing linker errors.
inline
VariablesAvoiding Multiple Definitions:
inline
variables can be defined in header files and included in multiple source files without violating the One Definition Rule (ODR).inline
variables as a single definition.Simpler Syntax:
inline
keyword provides a straightforward way to define variables without the need for separate declarations and definitions.Here’s an example:
// globals.h
#pragma once
inline int GlobalVar{42};
// main.cpp
#include <iostream>
#include "globals.h"
int main() {
std::cout << "GlobalVar: " << GlobalVar;
}
// other.cpp
#include "globals.h"
// Additional code can use GlobalVar here
g++ main.cpp other.cpp -o myProgram
./myProgram
GlobalVar: 42
Extern Keyword: Without inline
, you would need to declare the variable with extern
in the header file and define it in a source file. This method involves more boilerplate and separates the declaration and definition.
// globals.h
#pragma once
extern int GlobalVar;
// globals.cpp
int GlobalVar{42};
// main.cpp
#include <iostream>
#include "globals.h"
int main() {
std::cout << "GlobalVar: " << GlobalVar;
}
Static Keyword: Using static
for internal linkage prevents multiple definitions but limits the variable's scope to the defining file.
// globals.cpp
static int GlobalVar{42};
This means GlobalVar
cannot be accessed from other files.
inline
extern
and static
.Using inline
variables makes global variable management easier and more efficient, especially in large projects with multiple source files.
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