Don Slowik
Don Slowik

Reputation: 1120

C++ Global object definition depending on link order

Given main.cpp:

#include "A.h"

A a;

int main() {
}

A.h:

#ifndef A_HDR
#define A_HDR

class A {
 public:
  A();  
};

#endif

A.cpp:

#include <iostream>
#include "A.h"

A::A() {
  std::cout << "A ctor\n";
}

I create the relocatable object files main.o and A.o with g++ -c. Then:

> g++ main.o A.o
> ./a.out
Segmentation fault (core dumped)
> g++ A.o main.o
>./a.out
A ctor

Why the difference? If I move the definition of a from the global namespace into the scope of main it prints out A ctor as I expect.

> g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

Upvotes: 0

Views: 172

Answers (2)

Don Slowik
Don Slowik

Reputation: 1120

This seems to be described here, under the Non-local variables, Dynamic initialization section. cout is initialized in one translation unit, A.cpp, while a is initialized in another, main.cpp. The order within a single translation unit is sequenced as the order that the definitions appear, but between translation units is indeterminate as per section 3) there, Ordered dynamic initialization.

Upvotes: 0

kusstas
kusstas

Reputation: 111

Due to global objects in C++ creates in an undefined order In the first case: object "a" (which in global space) creates earlier that std::cout and we have failed on access to std::cout at "A::A()".

Upvotes: 1

Related Questions