Reputation: 3
I need to access the content of a struct, defined in the header of a c 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 A.c
#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";
}
}
Upvotes: 0
Views: 3621
Reputation: 2371
I don't see the real problem you are having. But to make the example work I've done the following changes.
In A.c:
#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
Upvotes: 1