简体   繁体   中英

accessing c-struct in c++

I need to access the content of a struct, defined in the header of ac file within in a c++ file.

The header-file struct.h has currently following format:

typedef struct {
    int x;
    int y;
} structTypeName;

extern structTypeName structName;

The struct is used and modified in the file Ac

#include "struct.h"

structTypeName structName;

int main(){

    structName.x = xyz;
    structName.y = zyx;
}

I now need to access the struct in a c++ file B.cpp (yes, it has to be c++). I've tried out a bunch of different ideas, but nothing has worked out so far. Can somebody please give me an idea how to realize this?

EDIT:

The c++ file looks following atm:

#include <iostream>

extern "C"{
    #include "struct.h"
}

int main(){

  while(true){

    std::cout << structName.x << "\n";

  }
}

I don't see the real problem you are having. But to make the example work I've done the following changes.

In Ac:

#include "struct.h"

structTypeName structName;

int c_main(void) { // new name since we can't have two "main" functions :-)
  structName.x = 123; // settings some defined values
  structName.y = 321;
}

And in B.cpp:

#include <iostream>
#include "struct.h"  // this declares no functions so extern "C" not needed

extern "C" int
c_main(void);  // renamed the C-main to c_main and extern declaring it here

int main() {
  c_main();  // call renamed C-main to initialize structName.

  // and here we go!
  while (true) std::cout << structName.x << "\n";
}

And to finally compile, link (using the C++ compiler), and run:

$ gcc -c A.c -o A.o
$ g++ -c B.cpp -o B.o
$ g++ A.o B.o -o a.out
$ ./a.out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM