Mastering C++ ODR: extern vs. inline

2025-09-09

Simply put, the ODR states that in a C++ program, every non-inline function, variable, class, or template must have exactly one definition. This definition must be unique across all translation units (i.e., .cpp files) that make up your program.

A translation unit is essentially a single .cpp file after the preprocessor has done its work (including all the #include files). The compiler processes each translation unit independently and generates an object file (.o or .obj). The linker then takes all these object files and combines them into a single executable.

If the linker finds multiple definitions for the same thing (like a function or a global variable), it throws an ODR violation error. This is a common point of frustration for many C++ developers.

This is a classic. You might define a global variable in a header file, thinking it's a good way to share it, but that's a big no-no.

Problematic Code

shared_data.h

// shared_data.h
int global_counter = 0; // This defines the variable

main.cpp

// main.cpp
#include "shared_data.h"
#include <iostream>

int main() {
    global_counter++;
    std::cout << "Counter: " << global_counter << std::endl;
    return 0;
}

another_file.cpp

// another_file.cpp
#include "shared_data.h"
// This file also sees the definition of global_counter
void do_something_else() {
    global_counter++;
}

When you compile and link main.cpp and another_file.cpp, the linker will see two definitions for global_counter and fail.

The Solution
extern and a single definition

The extern keyword is your friend here. It's a way of declaring a variable without defining it.

shared_data.h

// shared_data.h
extern int global_counter; // This declares the variable

shared_data.cpp

// shared_data.cpp
#include "shared_data.h"

int global_counter = 0; // This is the single, unique definition

Now, main.cpp and another_file.cpp can #include "shared_data.h", and the linker will be happy because there's only one definition of global_counter in the entire program (in shared_data.cpp).

Similar to global variables, defining a function's body in a header file will lead to an ODR violation if that header is included in more than one .cpp file.

Problematic Code

utils.h

// utils.h
#include <iostream>
void print_hello() { // Function body is in the header!
    std::cout << "Hello, world!" << std::endl;
}

main.cpp

// main.cpp
#include "utils.h"
int main() {
    print_hello();
    return 0;
}

another_file.cpp

// another_file.cpp
#include "utils.h"
void another_function() {
    print_hello();
}

This will also result in a linker error.

The Solution
Declare in header, define in source

The standard practice is to declare the function in the header file and define its body in a corresponding .cpp file.

utils.h

// utils.h
void print_hello(); // Declaration only

utils.cpp

// utils.cpp
#include "utils.h"
#include <iostream>

void print_hello() { // Single definition
    std::cout << "Hello, world!" << std::endl;
}

This is the most robust and common way to structure your code.

What if you want to define a function or variable in a header file? C++ has a way to handle this
the inline keyword.

The inline keyword tells the compiler and linker to relax the ODR for this specific item. It allows for multiple definitions, as long as they are identical. The linker will then pick one and discard the rest. This is often used for small, simple functions where the overhead of a function call is not desired.

inline for Functions

utils.h

// utils.h
#include <iostream>
inline void print_hello() { // 'inline' allows this in a header
    std::cout << "Hello, world!" << std::endl;
}

This is a common and perfectly valid use of inline for small utility functions.

inline for Variables (C++17 and later)

Since C++17, you can also use inline with variables. This is a game-changer for sharing variables in headers without ODR violations.

shared_data.h

// shared_data.h
#include <vector>
inline std::vector<int> my_data; // 'inline' allows this in a header

Using inline for variables is a modern and often cleaner alternative to the extern pattern for constants or simple shared data.

IssueProblematic Code ExampleCorrect ApproachAlternative (when appropriate)
Global Variablesint var = 0; in a header.extern int var; in header, int var = 0; in a .cpp.inline int var = 0; in header (C++17+).
Non-Inline Functionsvoid func() { ... } in a header.void func(); in header, void func() { ... } in a .cpp.inline void func() { ... } in a header.

cpp



Troubleshooting std::future_error: A Practical Guide

The std::future_error exception is thrown when an operation on a std::future or std::shared_future fails. This typically happens because the associated state of the promise or task has been lost or is no longer valid


Mastering std::tuple: Pitfalls and Modern C++ Alternatives

Here's a friendly breakdown of common issues, their explanations, and great alternatives with sample code.This is perhaps the biggest criticism


Modern C++ Error Handling and Expressiveness with C++23

Here's a friendly breakdown of some key C++23 features, including common potential troubles and alternative ways to handle things



C++ Input Streams: Why You Should Avoid std::ungetwc

Limited Buffer The most common problem is that you can only push back one character at a time. If you try to call ungetwc twice in a row


Mastering C++ Floating-Point Exceptions with std::feclearexcept

std::feclearexcept is a function in the <cfenv> header that helps you manage floating-point exceptions. Think of it as a "reset button" for these exceptions


Mastering C++ Localization: Beyond std::locale::classic

In C++, std::locale::classic represents a minimal "C" locale. Think of it as a basic, standardized set of rules for things like character classification (is it a letter


C++ I/O with basic_spanstream: Pitfalls and Solutions

The basic_spanstream constructor is pretty straightforward, but a few things often trip people upLifetime Management This is the biggest one


C++ forward_list::cend Explained: A Guide to Const Iterators

std::forward_list::cend returns a constant iterator that points to the element after the last element in a std::forward_list


Troubleshooting std::chi_squared_distribution::reset

When you're working with C++'s std::chi_squared_distribution, you might encounter a few common issues, especially when trying to reset the distribution


std::lognormal_distribution in C++: A Friendly Guide to Parameters (m, s) and the Normal Connection

Let's dive into the common issues, parameters, and alternative approaches in a friendly way!First, let's quickly review what std::lognormal_distribution does