0

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";

  }
}
KBS
  • 3
  • 1
  • 5
  • 1
    Possible duplicate of [How do I use extern to share variables between source files?](https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files) – Botje Jul 16 '19 at 08:57
  • Probably all you need is either add `extern "C" {...}` in your `struct.h` file or, if this is impossible around you `#include "struct.h"` – sklott Jul 16 '19 at 09:03
  • I already included `struct.h` via `extern "C" {}`. I still can't access the values of the variables. In my imagination something like `var = structName.x` should be sufficent to do this – KBS Jul 16 '19 at 09:11
  • @KBS Please add an example of the C++ code you are trying to access the struct with. I'll be easier to identify the problem when looking at the source code. – Bo R Jul 16 '19 at 09:27
  • If you are mixing C and C++ code, your `main` function should be in the C++ code. – Ian Abbott Jul 16 '19 at 09:30
  • @BoR I added my crappy piece of code which I use for testing. – KBS Jul 16 '19 at 09:50
  • @IanAbbott is this a must or a nice to have? it would be a shitload of work to bring `A.c` into c++... – KBS Jul 16 '19 at 09:52
  • Well you could rename A.c's `main` and call it from the C++ `main`. – Ian Abbott Jul 16 '19 at 10:23

1 Answers1

1

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
Bo R
  • 2,334
  • 1
  • 9
  • 17