I'm trying to share global variables within multiple .cpp
files. I had used extern
keyword, but it doesn't meet what I want.
At the first, I have had four files as:
***** common.hpp *****
#ifndef COMMON_HPP
#define COMMON_HPP
#include <iostream>
void printVar();
void printVarfromA();
void setVar(char *str);
#endif
***** Base.cpp *****
#include "common.hpp"
extern char *var;
void printVar(){
std::cout << var << std::endl;
}
void setVar(char *str){
var = str;
}
***** A.cpp *****
#include "common.hpp"
char *var = (char*)"This is var from A";
void printVarfromA(){
printVar();
}
***** main.cpp *****
#include "common.hpp"
int main(){
printVarfromA();
setVar((char*)"Var was Changed.");
printVarfromA();
return 0;
}
All thing goes fine, and the result was:
This is var from A
Var was Changed.
as I expected.
The problem arose when I have added a new file that shares the var
variable, let's say B.cpp
, where it contains a single line now:
***** B.cpp *****
char *var;
At this moment ld returned 1 exit status
ERROR appeared.
I have tried several methods and searched a lot, but I couldn't get any solution.
My question. How to share variable within multiple files in C++?
Aucun commentaire:
Enregistrer un commentaire