使用在不同源文件中定义的变量
Use variables defined in a different source file
我想从另一个CPP文件获得一个值
例如:fileone.cpp:
for (int i = 0; i < NSIZE(facerects); i++)
{
DetPar detpar;
detpar.x = facerect->x + facerect->width / 2.;
*gX=facerect->x;
detpar.y = facerect->y + facerect->height / 2.;
*gY=facerect->y;
}
和我想得到*gX, *gY的值在file2.cpp
在Java中,我们可以用getter =来做,但在c++中,什么是简单的方法?
如果全局变量在另一个文件中定义,则可以使用extern
公开它们。例如,如果在file2.cpp中有如下声明的变量:
int *gX; // a pointer to an integer
int *gY;
然后在main.cpp中你可以使用extern
:
// define these near the top of your cpp file and then use them wherever you need to
extern int *gX; // a pointer to an integer defined elsewhere in your program
extern int *gY;
但是,如果您打算按照源代码中的方式使用它们,至少要小心指向有效内存。最好简单地使用int
(而不是指针)。
此外,值得考虑使用全局变量的影响,因此在C/c++中讨论全局变量
fileone.h
#ifndef FILEONE_H
#define FILEONE_H
extern int *gX;
extern int *gY;
#endif
fileone.cpp
#include "fileone.h"
// These are made available externally via fileone.h
int *gX = NULL;
int *gY = NULL;
filetwo.cpp
#include "fileone.h"
// gX and gY are available, but are defined in fileone.cpp
相关文章:
- 在头文件中定义变量不会出错
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 在命名空间中定义变量
- 是否可以在C++中基于程序集输出(.dll或.exe)定义变量
- 用不同类型重新定义变量
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 定义变量类型
- 在命名空间中定义变量,但在测试中获取空值
- cmake没有定义变量
- C 中的继承:在亲子类中定义变量
- 在同一函数中定义变量及其静态等效项
- 如何在 Tensorflow C++ 中定义变量的自定义有状态 Op 保存值
- 如何将 int 和 int* 传递到函数中以定义变量
- 在定义变量时调用类函数
- 定义变量与模板
- 定义变量类型
- 为什么您可以在 switch 语句中的"默认"下定义变量,而不能在"case"下定义变量
- C 如何基于另一个变量和某些算术定义变量的值
- C 可以指向具有定义变量的函数
- C 定义变量设置值