2

Suppose there's a variable foo in another translation unit. The real type of foo is — for whatever reason — unknown in my C++ unit. I need to pass the address of this variable foo to a function bar that accepts a void pointer.

A solution that works for me on my machine with Clang is:

void bar(void *);

extern "C" char foo;  // foo is not really of type char

void function() {
  bar(&foo);
}

My questions are:

idmean
  • 14,540
  • 9
  • 54
  • 83
  • _what is a standard-conforming and portable way of achieving this?_ does it exist? –  Oct 28 '17 at 16:43
  • Why not simply forward declare the class and have an `extern` pointer to that global? Or have a function that returns a pointer to the global? – Nikola Dimitroff Oct 28 '17 at 16:49
  • @NikolaDimitroff I'm not sure I understand your suggestion. Which class should I forward declare? The type of `foo` is completely unknown. I could, of course, forward declare some class and declare `foo` to be of that type. Is that legal? Possibly not any more than using `char`, but I'm not sure. – idmean Oct 28 '17 at 16:53
  • @NikolaDimitroff And for the purpose of this question, changing the other translation unit is not an option. – idmean Oct 28 '17 at 16:55
  • You are linking with a translation unit over which you have no control? So you only have an object file? Since you are asking about standard conformity, I must ask - are you sure you can even link against that .obj file? If there's a difference between the compiler options / versions with which that translation unit was compiled and your own file there's no guarantee that the produced output from the linker will be usable. About my first question - I imagined that your foo had a type known in advance. Are you saying that `foo`'s type can change? What makes it change? – Nikola Dimitroff Oct 28 '17 at 17:10
  • @NikolaDimitroff `bar` is also provided by the other translation unit. In fact, I'm in control of the object file being linked against and it will be always legal to link against it. However, I'd prefer not to change it. And I'm just curious and want to see if this is possible. If not, I will change the other translation unit... – idmean Oct 28 '17 at 17:18
  • Maybe this could help: https://stackoverflow.com/questions/14697698/what-is-the-behavior-when-there-are-mismatched-types-between-an-extern-declarati – Amadeus Oct 28 '17 at 17:37

0 Answers0