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()andprint()functions because if I include the headers they are defined infoo.handbar.hthen the compiler won't compile because of the redefinition of the objectx.When I run the program I always get always the same value from the two functions
funcandprintalthough they reference a separate objectx.
The output:
5
5
Normally print prints 7 because includes foo.h which is initializing its x object to 7.
- I've declared
xin both headers asstaticto be linked internally in the TU it is used otherwise if removestaticfrom them then the two objects has external linking which causes the linker fail because of multiple definitions for the objectx.
I tried your code but with
foo.cppasand the output is
as you expect, so I think that you have a typo in
foo.cpp.