s*****w 发帖数: 215 | 1 问一个C++的初级问题
我在main.cpp的main函数里面call了一个function得到了一个值
我想用在别的cpp文件里,请问怎么做?
谁能写一点sample code?下面的code有问题吗?
main.cpp,
const char * myvalue;
Main(...)
{
myvalue=myFun();
}
在我的另外一个文件里面,比方说myfile.cpp
怎样使用这个myvalue这个variable呢?
myfile.cpp里面就一个方法:
Method(para.)
{
//请问在这里我怎样call到myvalue的值?
}
多谢! | d****n 发帖数: 1637 | 2 in myfile.cpp
extern char *myvar ; | O*******d 发帖数: 20343 | 3 在大项目里,用extern会有很多问题。抄一段网上的
The "extern" declaration in C is to indicate the existence of, and the type
of, a global variable or function. A global variable, or a global function,
is one that is available to all C modules (a single C module is typically a
single .c file). An extern is something that is defined externally to the
current module. In many cases, you can leave off the extern qualifier and
not notice any difference because the linker can collapse multiple
definitions to one. But the intent is then unclear in the code, and the code
is error prone in case of typos. It is much clearer to define the global in
one place, and then declare extern references to it in all the other places
. When refering to globals provided by a library, especially a shared
library, this is even more important in order to ensure you are talking
about the correct, common instance of the variable.
Declaring a variable as extern will result in your program not reserving any
memory for the variable in the scope that it was declared. For instance (as
example) if a program's source code declared the variable var as a global
volatile int in foo.c, to properly use it in bar.c you would declare it as
extern volatile int var.
http://wiki.answers.com/Q/What_is_the_use_of_extern_in_C
我一般是把所有的globals放在一个class里 public static variables。 并且封在一
个static函数里。
class Global
{
public:
static const char* GlobalA() { static const char* S = "Whatever"; return S; }
static int& GlobalB() { static int S; return S; }
static char*& GlobalC() {static char* S; return S; }
}
在其它文件里,
#include "Global.h"
Global::GlobalB() = 3;
Global::GlobalC() = "ABCD";
printf("%s\n", Global::GlobalA());
【在 d****n 的大作中提到】 : in myfile.cpp : extern char *myvar ;
| b***i 发帖数: 3043 | 4 简单程序可以直接extern,也可以包在namespace里面。
很多情况下你并不需要绝对的全局变量,而只是想获取其他程序里面的值。你可以把
function变成一个class里面的function,就可以在任何地方访问这个函数。class里面
可以用static变量。
myclass.h
class myclass{
public: static updateValue(){value = myFun()};
static int value;
whatever myFun(){};//static, private, it can even be moved outside
myclass
};
myclass.cpp
int myclass::value=0;
main里面
#include "myclass.h"
myclass::updateValue()
其他cpp
#include "myclass.h"
直接用myclass::value
myclass中的value就相当于一个全局变量。你的程序复杂了之后,很多function都会在
类中,其实java和C#就是所有的function都在class中。
【在 s*****w 的大作中提到】 : 问一个C++的初级问题 : 我在main.cpp的main函数里面call了一个function得到了一个值 : 我想用在别的cpp文件里,请问怎么做? : 谁能写一点sample code?下面的code有问题吗? : main.cpp, : const char * myvalue; : Main(...) : { : myvalue=myFun(); : }
| v**m 发帖数: 706 | |
|