0

I've been trying to figure out why changing the linking order of files in my project changes the behavior of the program, despite many sources saying that the order of object files (excluding libraries) shouldn't change anything. I've created a smaller reproducible example below:

// one.hpp
#include <vector>

extern std::vector<int> one;

// one.cpp

#include <vector>

std::vector<int> one = { 1, 2, 3, 4, 5 };

// two.hpp

#include <vector>

extern std::vector<int> two;

// two.cpp

#include <vector>
#include "one.hpp"

std::vector<int> two = one

// main.cpp
//g++ one.cpp two.cpp main.cpp
std::cout << one.size() // 5
std::cout << two.size() // 5
//g++ two.cpp one.cpp main.cpp
std::cout << one.size() // 5
std::cout << two.size() // 0

Logically, this makes sense. Since one doesn't "exist" yet, there is nothing for two to be assigned as, but this conflicts with what I have read online about the linking order of object files, and I also don't understand the technical reasons why this happens. This happens with both clang++ and g++, so it seems to be intended behavior.

Why is the two vector empty if the one.o file is linked after the two.o file?

BeyondPerception
  • 534
  • 1
  • 6
  • 10

0 Answers0