Linkage of Constants
Why do const and constexpr variables have internal linkage by default?
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.
Internal Linkage
- Internal Linkage: By default, constandconstexprvariables are only accessible within the file they are defined in.
- Reasoning: This prevents different parts of the program from inadvertently modifying these variables and ensures their values are consistent wherever used.
Here's an example:
// constants.cpp
const int MaxUsers{100};
constexpr float Pi{3.14159f};Explanation
- Consistency: Having internal linkage ensures that MaxUsersandPiare consistent withinconstants.cppand can't be altered by other files.
- Avoiding Conflicts: Internal linkage prevents multiple definition errors that could arise if these variables were defined in multiple files.
Changing Linkage
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
./myProgramMaxUsers: 100
Pi: 3.14159Benefits of Internal Linkage
- Encapsulation: Keeps the variable's scope limited to the defining file, promoting encapsulation and modularity.
- Avoids Multiple Definitions: Prevents multiple definition errors and ensures a single definition per translation unit.
- Consistency: Ensures the value of constandconstexprvariables remains consistent across the file, avoiding accidental changes from other parts of the program.
Summary
- Default Behavior: By default, constandconstexprvariables have internal linkage, making them file-local.
- Purpose: This design choice avoids linking conflicts and ensures value consistency.
- Modifying Linkage: If needed, their linkage can be changed to external using the externkeyword.
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.
Internal and External Linkage
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