c++ - 使用在不同源文件中定义的变量

标签 c++ c visual-studio-2010 pointers

我想从另一个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;

    }

我想获取 file2.cpp 中 *gX , *gY 的值

在 Java 中,我们可以使用 getters= 做到这一点,但在 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 (不是指针)会更好。

此外,值得考虑使用全局变量的影响 SO discussion of global variables in C/C++

关于c++ - 使用在不同源文件中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975039/

相关文章:

c++ - 预编译 header 的实际工作原理

c++ - 如何在 linux 中获取 C++ 中的接口(interface)列表?

visual-studio-2010 - 将svn集成到VS-2010 IDE中有哪些不同的方式

visual-studio-2010 - 在 Windows 7 中禁用/删除 .NET Framework 3.5 语言包

c++ - 使用 cmake 将 Eigen 库添加到 C++ 项目

c++ - 按行反转 ostringstream

c - 使用宏在 C 中实现通用 vector 。这是个好主意吗?

c++ - 如何定义指向类成员函数的指针

c++ - 核心文件分析

c - 写入一个大文件或多个小文件