c ++, declare a struct as a global variable

0

C ++, when declaring a struct as a global variable, later I can not access it from an object (class) ... The development environment consists of three files:

  • the 1st file contains the main pgm, so the variable is defined:

    struct  stXXX {
        TIMESTAMP_STRUCT  timestamp; // Horario de generación del registro en tabla VarProceso
        double            contador;  // Cantidad de bolas ingresadas
        float             diametro;  // Diametro de bolas ingresadas
    } stXXX;
    
  • the 2nd file is a header for the declaration of the class.

  • the 3rd file contains the code (c ++) of the object that is invoked from the 1st file.

The struct is declared before the main() in the 1st file, if I use it in the main pgm, it does not generate any errors.

The compiler warns me that the "identifier stXXX is undefined" when I use it in the 3rd file.

I manage the project with Microsoft Visual Studio Community 2015

My questions are:

  • a.- Can I do what I'm doing?
  • b.- How should I declare it to be visible from the code where the object is programmed (3rd file)? or
  • c.- How does the reference from the 3rd file?
asked by HGT 25.10.2017 в 04:01
source

1 answer

0

Your problem is clearly indicated in the error you receive:

  

"identifier stXXX is undefined"

I translate it:

  

"el identificador stXXX no está definido"

In C ++ the code files (normally with cpp extension) can see all the definitions that are contained in the same file or those that have been added by an inclusion ( #include ), these code files are they are also known as "Translation Units" (UdT).

The definitions of a UdT are not visible in other UdT, so if your structure stXXX is in "1er_fichero.cpp" and you use it in "3er_fichero.cpp" , the UdT of 3er_fichero will not know of the existence of what is defined in the UdT of 1st file and consequently complain that " the identifier stXXX is not defined ".

  

Can you do what I'm doing?

As you can see from the compilation error: No.

  

How should I declare it to be visible from the code where the object is programmed (3rd file)?

In 3er_fichero.cpp you must include the file in which stXXX is defined, which if I'm not wrong is 2do_fichero.hpp :

#include "2do_fichero.hpp"

int main()
{
    // ... hacer cosas ...
    return 0;
 }
  

How does the reference from the 3rd file?

Once the inclusion has been added, you can create instances of the stXXX object normally.

    
answered by 26.10.2017 / 12:08
source