2

Api.cpp:

int (*theFunc) (int);
theFunc = (int (*) (int)) DlSym(hSo, "theFunc");

So far so good.

Now, I want to make a header so that other cpp files can also call theFunc.


Api.h: per How to declare function pointer in header and c-file?

extern int (*theFunc)(int);

/usr/bin/ld: Warning: type of symbol `theFunc' changed from 2 to 1 in Api.o

OK, so this is a warning that theFunc is seen as a function from one compilation element and as a variable in another. (Reference) This seems like bad things will happen at runtime.

This seems to be a proper declaration, what am I doing wrong?

Edit: Actually running in linux, so use DlSym not Microsoft GetProcAddress() call

Community
  • 1
  • 1
jcwenger
  • 11,383
  • 1
  • 53
  • 65

2 Answers2

0

According to the linked post, condense it to one line, not two in the .cpp file. So the .h seems right, and put this in the .cpp file:

int (*theFunc) (int) = (int (*) (int)) GetProcAddress(hDll, "theFunc");

You're not doing declaration and assignment in one shot like the linked answer is. With what I posted above, you will be.

Kevin Anderson
  • 6,850
  • 4
  • 32
  • 54
  • I can't call GetProcAddress from a variable definition, because I don't have a handle to the dll until runtime inside a function, after I've called LoadLibrary() – jcwenger Apr 18 '12 at 21:08
  • For "defining" the location of an extern variable like this, any assignment should work, so maybe try NULL-assigning the variable in the .cpp file, and then "really" assigning it later. – Kevin Anderson Apr 18 '12 at 22:03
  • Initialization is not required for definition. And that's not even the problem. The variable is defined and it shows, I can find it it objdump -t just fine. The problem is that in other compilation units, extern int (*theFunc)(int); is seen as a function declaration, not a pointer-to-function. – jcwenger Apr 19 '12 at 13:45
0

You probably should not include Api.h

Alternatively you may work with macros in a way that api.h behave somewhat different when included by api.cpp. MicroSoft has done/do such things.

api.h

#ifdef _API_
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN int (*theFunc)(int);

api.cpp

#define _API_
#include "api.h"
...

other.cpp

#define _OTHER_
#include "api.h"
...
stefan bachert
  • 9,413
  • 4
  • 33
  • 40
  • This warn occurs regardless of whether I do or don't include Api.h from Api.cpp. – jcwenger Apr 18 '12 at 21:09
  • Also, same results (ld warn) using your defines – jcwenger Apr 18 '12 at 21:15
  • And I'm using linux gcc, not MS, despite my original post. Buried further in, I'm actually calling DlSym. There's a stupid wrapper around this third party .so that uses MS function names to load the .so, they can be "Cross Platform" Ugh. – jcwenger Apr 18 '12 at 21:22