0

i want to get a value from another cpp file

for example this one is in 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;

    }

and i want to get the value of *gX , *gY in file2.cpp

in java we can do that with getters= but what is the easy way to do it in c++?

harper
  • 13,345
  • 8
  • 56
  • 105
TIBOU
  • 337
  • 2
  • 6
  • 16

2 Answers2

1

If global variables are defined in another file, you can expose them using extern. For example, if in file2.cpp you have variables declared as follows:

int *gX; // a pointer to an integer
int *gY;

Then in main.cpp you can use the variable using 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;

However, at least be careful to point to valid memory if you are going to use them the way you have in your source code. It would be better to simply use int (not pointers).

Also, it's worth considering the impact of using global variables SO discussion of global variables in C/C++

Community
  • 1
  • 1
axon
  • 1,190
  • 6
  • 16
  • i get this error error LNK2001: unresolved external symbol "int gX" (?gX@@3HA) . when i used your method with int – TIBOU Jun 07 '13 at 02:24
0

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
paddy
  • 60,864
  • 6
  • 61
  • 103
  • However, generally speaking, avoid extern variables at all cost. Otherwise, the organization/architecture of your code will be a mess. – J-Mik Jun 07 '13 at 02:08
  • I don't agree with sweeping generalisations like that, @DoesntMatter. If used tastefully, this sort of thing is just fine, and quite normal. For this particular case I don't think extern variables are appropriate though =) – paddy Jun 07 '13 at 02:11
  • i get this error error LNK2001: unresolved external symbol "int gX" (?gX@@3HA) – TIBOU Jun 07 '13 at 02:17
  • That means you either haven't defined it globally in `fileone.cpp` as I showed, or you didn't link properly. Are both the cpp files part of the same project? – paddy Jun 07 '13 at 02:28