我们是否应该在项目中包含的所有文件中声明外部变量
Should we declare extern variables in all the files included in a project?
我一直在尝试使用'Extern'关键字的一些事情。我写了这个基本功能,我不确定为什么我的打印功能不起作用。请帮助我理解它。
test1.h
#pragma once
#include<iostream>
using namespace std;
extern int a;
extern void print();
test1.cpp
#include "test1.h"
extern int a = 745;
extern void print() {
cout << "hi "<< a <<endl;
}
test2.cpp
#include"test1.h"
extern int a;
extern void print();
int b = ++a;
int main()
{
cout << "hello a is " << b << endl;
void print();
return 0;
}
Actual output :
hello a is 746
Expected output:
hello a is 746
hi 746
test1.cpp
#include "test1.h"
int a = 745; //< don't need extern here
void print() { //< or here
cout << "hi "<< a <<endl;
}
test2.cpp
#include"test1.h"
/* we don't need to redefine the externs here - that's
what the header file is for... */
int b = ++a;
int main()
{
cout << "hello a is " << b << endl;
print(); //< don't redeclare the func, call it instead
return 0;
}
您仅在声明变量/函数时才需要使用外部,并在其中一个CPP文件中定义变量,其中包括标头。
所以,您想做的是
test1.h
#pragma once
#include<iostream>
using namespace std;
extern int a;
extern void print();
test1.cpp
#include "test1.h"
int a = 745;
void print() {
cout << "hi "<< a <<endl;
}
test2.cpp
#include"test1.h"
int b = ++a;
int main()
{
cout << "hello a is " << b << endl;
print();
return 0;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 用"=default"声明的函数应该只在头文件中执行
- 调用在 HXX 文件中声明的静态数据成员
- 如何在 c++ 的不同文件中声明类?
- 如何在头文件中声明类模板(由于循环依赖关系)
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 在.cpp文件之间传递结构声明,而不使用全局头文件
- 为什么要将函数声明和定义放在单独的文件中
- 枚举前向声明与头文件
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 在带有类型保护的模板文件中使用前向声明
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 在多个头文件中从接口声明被覆盖的函数时,如何避免重复代码?
- 应该在类中的文件声明为静态
- 是否应从头文件声明中排除辅助函数?(C++)
- 哪个C++头文件声明 strlen
- 如何为头文件声明“#include”以避免“error lnk2005”
- 打开文件和关闭文件声明定位:最佳做法,优点,缺点
- 说双向文件声明不隐式设置标志是否正确