tags:

views:

59

answers:

3

Hi,

I have a string variable as:

string name = "MyName"; in one cpp file.

How can i use the same string variable in another class within the same project.

+4  A: 

extern string name; in the other files, and then link the objects together.

Borealid
A: 

you could try

inline string GetName(){return "MyName";}

you can just put that in a header

that way you don't have to worry about putting the definition in one random .cpp file

you could also do

#define NAME "MyName"

this is usually bad, firstly, because the compiler might struggle a bit more to find that the string is the same string used everywhere. also there are other problems with macros ect (like namespace)

the one good thing about this method is it makes it easier to glue strings together, due to the way the compiler automatically concatenates adjacent literal strings after macro expansion (the whole preprocessor step)

i.e., you could go:

printf("My name is " NAME);
matt
A: 

I think you can make a config file and do a #define for that example

#define NAME "MYName"


of make a char * a = "MYName";

And include config.cpp in every file should work good.

Arjit
char* = "MYName" is ill formed C++ code.
Maxim Yegorushkin
@Maxim: it's well-formed, but deprecated. Trying to use the non-const pointer to modify the string literal is ill-formed.
Mike Seymour
You are right. Forgot that C compatibility requires that.
Maxim Yegorushkin