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

Use variables defined in a different source file

本文关键字:定义 变量 源文件      更新时间:2023-10-16

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