Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a linker error to #include this file more than once?

Tags:

c++

This question isn't so much a 'how to solve' question as its a question about why doesn't this work?

In C++ I can define a bunch of variables that I want to use across multiple files in a few ways.

I can do it like this:

int superGlobal;
#include "filethatUsesSuperglobal1.h"

int main()
{
  // go.
}

That way ONLY works if "filethatUsesSuperglobal1.h" has its entire implementation there in the header and no attached .cpp file.

Another way (the "morer correcter" way) is to use extern:

externvardef.h

#ifndef externvardef_h
#define externvardef_h
// Defines globals used across multiple files.
// The only way this works is if these are declared
// as "extern" variables
extern int superGlobal;

#endif

externvardef.cpp

#include "externvardef.h"
int superGlobal;

filethatUsesSuperglobal1.h

#include "externvardef.h"
#include <stdio.h>
void go();

filethatUsesSuperglobal1.cpp

#include "filethatUsesSuperglobal1.h"
void go()
{
  printf("%d\n", superGlobal );
}

main.cpp

#include <stdio.h>
#include "externvardef.h"

#include "filethatUsesSuperglobal1.h"

int main()
{
  printf( "%d\n", superGlobal ) ;
  go() ;
}

This is a small point and a somewhat nit picky question, but Why do I need to declare it extern - should not the #include guards on "externvardef.h" avoid redefinition?

Its a linker error, even though that header file has #include guards around it. So its not a compiler error, its a linker error, but why.

like image 883
bobobobo Avatar asked Nov 28 '22 12:11

bobobobo


1 Answers

Think about if from the code perspective - there is this symbol superGlobal that points at an integer.

You have a bunch of .o files to link together into a single executable. Each of the .o files has it's own superGlobal symbol. Which should the linker use?

The extern declaration says: another of the compilations units (.o files) is going to declare this symbol, so I can use it. Thus there is only one copy so the linker knows what to do.

like image 170
Douglas Leeder Avatar answered Dec 18 '22 07:12

Douglas Leeder