[英]How to declare variable in different file?
I'm new to C++ and just trying to separate function into files. 我是C ++的新手,只是想将函数分成文件。 Here is an example from one of my assignment. 这是我分配的一个例子。 When I compile it, the message shows: 当我编译它时,消息显示:
'b' is not declared 未声明“ b”
When I add #include "q1b.cpp"
to q1a.cpp
, it fail. 当我将#include "q1b.cpp"
添加到q1a.cpp
,它将失败。 How can it run by only changing q1a.cpp
? 仅更改q1a.cpp
如何运行? Glad to know the concept. 很高兴知道这个概念。
//q1a.cpp
#include <iostream>
#include "q1b.h"
using namespace std;
int main() {
calC();
cout << b << endl;
return 0;
}
//q1b.cpp
#include "q1a.h"
#include "q1b.h"
int b=1;
void calB(int i) {
b = calA(i) + 1;
}
void cal() {
calB(calA(b));
}
//q1a.h
int calA(int i) {
return i*10;
}
//q1b.h
void calC();
Declare the variable with extern
specifier. 使用extern
说明符声明变量。
//q1a.cpp
#include <iostream>
#include "q1b.h"
using namespace std;
extern int b; // add this line
int main() {
calC();
cout << b << endl;
return 0;
}
If the constraint "by only changing q1a.cpp" weren't there, you should add the declaration of variable to q1b.h
because the variable is defined in q1b.cpp
. 如果没有“仅更改q1a.cpp”约束,则应将变量声明添加到q1b.h
因为该变量是在q1b.cpp
定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.