Reputation: 319
I am trying to use a data (or even functions) from one .h file in a number of other .cpp files and I am getting a compiler area thats suggesting linking error. I know this will be really simple but I am hurting myself with it. I am using Xcode, however I don't think thats the problem, it's far more likely to be me being a bit think!
My version is more complex so I will use a very simply example of what I am looking for.
If I have a header file data1.h:
int a,b; // etc
Then one .cpp file, say setdataA.cpp:
#include "data1.h"
void set_a(int numb){ a=1;}
Then another, say setdataB.cpp:
#include "data1.h"
void set_b(int numb){ b=10;}
I am wondering what I am doing wrong, maybe if I should even be trying to do such a thing.
I have even tried to swap
#include "data1.h"
in setdataB.cpp to
#include "setdataA.h"
and still it don't work!
Upvotes: 0
Views: 207
Reputation: 319
I figured out what I was doing wrong. It was to do with my misunderstanding of how header files actual work and actual what I was trying to do was so simple/elementary that people (that answered me) were mistaken as to what I was actually trying to do (I apologise to them).
What I should have been done is in data1.cpp is put
int a;
int b;
void set_a(int numb) { a=numb; }
void set_b(int numb) { b=numb; }
int get_a() { return a }
int get_b() { return b }
Then in data.h put
void set_a(int numb);
void set_b(int numb);
int get_a();
int get_b();
data.h could then be included in as many files as wanted and setting or getting of either a or b can be achieved by just calling one of the functions rather than directly changing or calling the value of them.
Hopefully this may help people if they ever are trying to work this out.
(Also sorry for a rather long time to get back and answer this as I was a bit embarrassed when I figure it was so elementary that I was a bit ashamed about my lack of knowledge in asking the question. And secondly as this was my first question on stack, I also think the my question could have be asked better to give more idea to what I was asking for)
Upvotes: 1
Reputation: 2472
First, it would help if you provided the actual error.
Second, you should wrap your header contents with an INCLUDE GUARD like this:
#ifndef MY_UNIQUE_INCLUDE_GUARD
#define MY_UNIQUE_INCLUDE_GUARD
... // header contents
#endif
Third, your issue is probably that the ints a and b are being defined in both .cpp files (via inclusion by the header) resulting in multiple defined symbols.
Instead, you probably mean to declare them in the header without defining them:
extern int a;
extern int b;
Then, in the .cpp files, define them:
int a;
int b;
Just define them in exactly one .cpp file. You can define a in one .cpp file and b in another .cpp file if that makes sense for your project.
Upvotes: 5