Re: Mulitiple definitions
Re: Mulitiple definitions
Is it possible to get an answer with out being redirected to a article? Does anyone have a C++ answer for me?
Re: Mulitiple definitions
You should probably read the article regardless, as I believe you'd not only find the answer to your current question, but probably your second, and third, etc that you are likely to run into later.
If you want the short answer, it's because of multiple inclusion.
Code:
#ifndef HEADER_H_
#define HEADER_H_
/* header.h */
char test[MAX_PATH]="file.txt";
#endif /*FUNCS_H_*/
Re: Mulitiple definitions
In one cpp file define the variable, in all other translation units that need the variable declare as extern.
Re: Mulitiple definitions
Quote:
Originally Posted by
Russco
In one cpp file define the variable, in all other translation units that need the variable declare as extern.
Russco is right. The error is not because of multiple inclusion but cause the global variable was DEFINED in the header so that each cpp that includes the header would create a new instance of that variable (symbol). The linker then will complain because of that.
So, in the header you would need only a DECLARATION what is made by the extern keyword. And one and only cpp MUST have a definition of the variable simply like
Code:
// header
...
extern char test[MAX_PATH];
...
// first.cpp
#include "header.h"
char test[MAX_PATH] = "file.txt";
You see the use of shared global variables among source files is quite tricky. You better use a class and define a static public member.
Code:
// global.h
#ifndef GLOBAL_H
#define GLOBAL_H
class Global
{
public:
static char * getTest()
{
static char test[MAX_PATH] = "file.txt";
return test;
}
};
#endif
// any cpp
#include "global.h"
...
// set another file
strcpy(Global::getTest(), "anotherfile.txt");
// use filename
ifstream ifs(Global::getTest());
Beside of using plain char pointers the above is much easier and a C++ solution. And the char pointer easily could be replaced by a std::string.
Re: Mulitiple definitions
Thanx for the solution itsmeandnobodyelse, I've been trying to understand the concept of classes public and private over and over. Reading many many tutorials about it and it just seems to slip my mental grasp but I'll keep trying to learn and understand it. However, I'm having the same error. I declared it in the first .cpp like you said and extern in the header and the same error exists. What gives?
Re: Mulitiple definitions
Just one thing. Rather than using
#ifndef GLOBAL_H
#define GLOBAL_H
....
......
#endif
you can simply use #pragma once
Re: Mulitiple definitions
Quote:
Originally Posted by hypheni
Just one thing. Rather than using
#ifndef GLOBAL_H
#define GLOBAL_H
....
......
#endif
you can simply use #pragma once
But be warned that #pragma once is non-standard. I suggest that you use normal header inclusion guards.