How internal linking works and why I get the same value for the two objects?

68 views Asked by At

I am trying to understand internal linking and external linking so I've tried this program:

// foo.h
static int x = 7; // makes x internally linked
void print();

// foo.cpp
#include "bar.h"
#include <iostream>

void func()
{
    std::cout << x << '\n';
}

// bar.h
static int x = 5; // internally linked. without "static" itis linked externally
void func();

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

void func()
{
    std::cout << x << '\n';
}

// driver program
    #include <iostream>

// forward declarations
void func();
void print();


int main()
{
    func();
    print();
}
  • I've removed inclusion guards (or #pagma once) for the sake of brevity. I also forward-declare func() and print() functions because if I include the headers they are defined in foo.h and bar.h then the compiler won't compile because of the redefinition of the object x.

  • When I run the program I always get always the same value from the two functions func and print although they reference a separate object x.

The output:

5
5

Normally print prints 7 because includes foo.h which is initializing its x object to 7.

  • I've declared x in both headers as static to be linked internally in the TU it is used otherwise if remove static from them then the two objects has external linking which causes the linker fail because of multiple definitions for the object x.
1

There are 1 answers

0
dodooft On

I tried your code but with foo.cpp as

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

void print()
{
    std::cout << x << '\n';
}

and the output is

5
7

as you expect, so I think that you have a typo in foo.cpp.