2

Suppose I have a dylib (not written by me) that exports a function "Foo". If I declare it as

extern "C" void Foo(void);

and try to call it, I get a linker error saying that _Foo is missing. How can I deal with this without modifying the dylib? Maybe some obscure linker flag, or Clang markup on the declaration, to make it not expect the underscore?

JWWalker
  • 22,385
  • 6
  • 55
  • 76
  • Are you using [`dlopen`](http://linux.die.net/man/3/dlopen) and `dlsym` to get a pointer to the exported function? – Praetorian Sep 30 '13 at 19:10
  • @Praetorian: no, I was hoping not to have to get function pointers. – JWWalker Sep 30 '13 at 19:14
  • Does CLANG linker support DEF files? – Yury Schkatula Sep 30 '13 at 19:25
  • @JWWalker Then you'll have to look for a linker option that lets you bind statically to a dylib. MSVC, for instance, can resolve function addresses from a DLL at link-time, thus avoiding having to manually `LoadLibrary` and `GetProcAddress` to get a function pointer. – Praetorian Sep 30 '13 at 19:29

2 Answers2

6

For a small number of these functions, its easiest to use a gcc/clang extension (perfect for OS X) to declare the external linkage to be assembly:

extern void Foo(void) asm ("Foo");

See this answer for more detail.

Community
  • 1
  • 1
sfstewman
  • 5,589
  • 1
  • 19
  • 26
  • Oh nice, this looks exactly what the OP wants. You can macroize this: `#define NO_UND(func) extern void func(void) asm(#func);` – nneonneo Sep 30 '13 at 21:35
  • Cool. For the record, before this was posted, I thought of a somewhat less good approach: Build a "glue" library using the linker's `-alias` or `-alias_list` option. – JWWalker Sep 30 '13 at 22:16
2

You can try to load the function manually using dlsym:

#include <dlfcn.h>

static void (*Foo)(void);

/* In some initialization function... */
Foo = dlsym(RTLD_DEFAULT, "Foo");
nneonneo
  • 171,345
  • 36
  • 312
  • 383