Header files - C include guards and multiple definition errors

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have a situation where I need to include a header file (stack.h) in 2 .cpp files.

The set up is as below:

//------"stack.h"------//
std::stack<int> s;
int a;
void doStackOps();
void print();

//------"stack.cpp"------//
#include "stack.h"


//------"main.cpp"------//
#include "stack.h"

Question 1

My header file contains 2 variables and 2 methods. I seem to be getting multiple definition errors only for the variables, why is this the case? Should it not be complaining about the redefinition of the functions as well?

The error looks like :

duplicate symbol _stacks in:
/Users/.....stack.o
/Users/......main.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Question 2

http://stackoverflow.com/questions/14909997/why-arent-my-include-guards-preventing-recursive-inclusion-and-multiple-symbol/28652792#28652792 http://stackoverflow.com/questions/14909997/why-arent-my-include-guards-preventing-recursive-inclusion-and-multiple-symbol/28652792#28652792 is that we use

inline or static 

where inline is preferred

    • Why is inline preferred over static?
    • inline can only used with functions?

Since I only get the error on the variable, the error goes away when I redefine the stack s as :

static std::stack<int> s; 
static int a; 

Any ideas on what might be happening here? If it helps, I am using Xcode 6. Would really appreciate any help!

Thanks in advance.

Answers

There are multiple definition errors because stack.cpp does:

stack<int> s;

and main.cpp also defines a stack:

stack<int> s;

You have two different global objects defined with the same name which causes undefined behaviour (luckily your linker diagnoses it).

Instead, what you probably intended to do was to have a single stack that is referred to by several different units. To accomplish that you can only have the line that defines a stack appear once. (Remember that #include is just a straight text replacement; your code behaves the same as if you copy-pasted the contents of stack.h into the body of each .cpp file).

The other units need to have a line which says "There is a stack<int> called s defined somewhere (but not here)" and the code for that is:

extern stack<int> s;

So you should put that line in your header file, and put stack<int> s; in exactly one .cpp file - doesn t matter which.


In the case of the functions, you do not define any functions in the header, only declare. If you defined a function in the header (e.g. void print() { }) then you would have the same multiple definition error causing undefined behaviour.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/28666366/c-include-guards-and-multiple-definition-errors

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils