In C++, const
and constexpr
variables have internal linkage by default to ensure that their values remain consistent across translation units and to avoid potential linking conflicts.
const
and constexpr
variables are only accessible within the file they are defined in.Here’s an example:
// constants.cpp
const int MaxUsers{100};
constexpr float Pi{3.14159f};
MaxUsers
and Pi
are consistent within constants.cpp
and can't be altered by other files.You can give const
and constexpr
variables external linkage using the extern
 keyword:
// constants.h
#pragma once
extern const int MaxUsers;
extern constexpr float Pi;
// constants.cpp
#include "constants.h"
const int MaxUsers{100};
constexpr float Pi{3.14159f};
Below, we access and use these variables:
// main.cpp
#include <iostream>
#include "constants.h"
int main() {
std::cout << "MaxUsers: " << MaxUsers << '\n';
std::cout << "Pi: " << Pi << '\n';
}
g++ main.cpp constants.cpp -o myProgram
./myProgram
MaxUsers: 100
Pi: 3.14159
const
and constexpr
variables remains consistent across the file, avoiding accidental changes from other parts of the program.const
and constexpr
variables have internal linkage, making them file-local.extern
keyword.Understanding the default internal linkage of const
and constexpr
variables helps in writing clear and conflict-free code, ensuring variables are used as intended without unintended side effects.
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