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
In order to resolve this, the answer suggested for a similar situation here Why aren't my include guards preventing recursive inclusion and multiple symbol definitions? 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.