0

I define the struct A in the a.cpp in the first.

       // a.cpp
       #include"a.h"
       struct A {                                                                                                       
           A(int num):a(num){}
           int a;
       };
         
       A obj{1};
       A* obj_ptr = &obj;
        

and in the header, i made the forward declaration of A and declaration of obj_ptr:

   // a.h
   struct A;                                                                                                        
   extern A* obj_ptr;

then i want to use obj in another cpp file called b.cpp, but compiler reported error: invalid use of incomplete type "struct A"

    // b.cpp
    #include<iostream>  
    #include"a.h"                                                                                           
                        
    int main(){         
        std::cout << obj_ptr->a << std::endl;
    } 

One way to fix it is to move the definition of A from a.cpp to a.h, but I wonder if there is any way else to fix it?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Yushin Liu
  • 31
  • 4

2 Answers2

0

To compile correctly this statement in main

std::cout << obj_ptr->a << std::endl;
             ^^^^^^^^^^

(more precisely the underlined expression) the compiler needs to know the structure definition of the object pointed to by the pointer obj_ptr. Otherwise it will be unable to determine what is a.

Place the structure definition in a header and include the header in each module where the full structure definition is required.

One way to fix it is to move the definition of A from a.cpp to a.h, but I wonder if there is any way else to fix it?

There are no other ways to provide the definition of the structure to the compiler without placing the definition in each compilation unit where it is required. Each compilation unit is compiled independently of other compilation units.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

One way to fix it is to move the definition of A from a.cpp to a.h, but I wonder if there is any way else to fix it?

No.

Well I say no, but what I mean is that is the most sensible solution most likely.

In theory, you could instead move definition of main into a.cpp, or copy the class definition into b.cpp. These would work, but are they appropriate for your design? Probably not, but we cannot know.

eerorika
  • 232,697
  • 12
  • 197
  • 326