Not sure if I am being really silly but doing learning and it seems that I cant use the same header file in multiple cpp files. It keeps giving linker errors when trying to compile, is this right? All I want to do is centralise some variable data so I can use it across multiple cpp files. Any pointers or help would be greatly appreciated... or another way to achieve this?
userdata.h
#ifndef __USER_DATA_H__
#define __USER_DATA_H__
int target1;
int temps;
#endif // _USER_DATA_H_
then in multiple files I do
s1.cpp
#include "userdata.h"
x2.cpp
#include "userdata.h"
z3.cpp
#include "userdata.h"
The problem is that you are defining variables target1 and temps in the header file rather than just declaring that they exist. The way you've coded it, s1, x2 and z3 all allocate space for the two variables. When the linker creates the program, it doesn't know whose space to use.
The way to handle this is to declare the variables in userdata.h and define them in just one of the cpp files. That way only one file allocates space for the variables and the linker knows right where they are:
userdata.h:
Hi dhayden many thanks for the reply. So I take it that extern creates an empty shell and in s1.cpp you initialising them. But it seems that you cant just simply use the value like target1 or temps in code without int? Sorry if it seems a silly question.. Would this be achievable :
s1.cpp
Please note that global variables are widely considered bad practice, regardless of the language you use. Google search "why are global variables bad" and you will find plenty of sources explaining it in detail:
Hey I just wanted to ask why I don't seem to get any errors when I have a header file with declarations like
1 2 3 4 5 6 7 8 9 10 11
// constants.hpp
// no cpp file
// include guards removed for brevity
namespace values {
constdouble Pi = 3.14....;
constdouble Sqrt2 = 1.4142...
}
namespace headers {
const std::string Separate ( "[Separate]" );
...
}
I'm pretty sure I'm including it into more than one implementation or other header file, so why doesn't the linker complain about multiple definitions?
I could be wrong, but aren't constants by nature defined and declared once, and exist in a single memory space? I would think the compiler would treat them differently than non-constants?
Yeah they're all in the project tree, and it compiles/runs fine, but no I'm not sure, I guess they aren't actually being linked together or something.
So for maximum compatibility I should be defining constants like Pi as extern and then defining them in a "constants.cpp" file?
EDIT: Oh I saw your other post LB and Texan40, I understand now. Thanks.