XCode/Cocoa - Calling .cpp function from .c file

Status
Not open for further replies.

spagthorpe

Ars Tribunus Angusticlavius
7,304
This shouldn't be a big deal, so I'm assuming that there might be some thing with XCode that I'm not getting, or I'm overlooking the obvious here.

I have an existing minimal Cocoa application in XCode. I have an existing pile of C++ code to add to it. It's mostly self contained, but I need to at least call the function MainLoop() located in one of the .cpp files. I have a shim file, shim.c, with a few functions in it that get called directly from the AppDelegate.m file. No problem there, the shim functions get called.

What I can't seem to do, is call the MainLoop() function from the shim.c file. I wrapped the declaration in the .h for the .cpp file:

Code:
extern "C" {

int MainLoop( void );

}


What I get is:

Code:
Undefined symbols for architecture x86_64:
  "_MainLoop", referenced from:
      _StartMainLoop in shim.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


I just don't know if there is some weird build flag, or something else I need to do here. I've tried messing around with this for a while, and not really understanding the behavior.
 

Bhelyer

Well-known member
2,231
andrewme":1faqhc2d said:
Sounds like you forgot to also wrap the definition of MainLoop in "extern C". That's why the symbol doesn't exist.

Yeah. C++ doesn't know that you want `extern "C" int MainLoop(void)` as the signature for the function in your C++ file, and so it mangles it like usual which means _MainLoop isn't in the object file.
 
Also, your .c shim file might be unnecessary depending on what you've placed in there.

But if it's plain c->c++ for the sole use of interfacing with cocoa/Obj-C it may be worth a look into setting a couple of your cocoa files at the boundary to be compiled as Obj-C++? I've not used it myself, but I understand it allows the one .mm file to properly deal with both Obj-C and C++ objects (and headers). Currently thats about all I understand of it :)

Whether it's easier/better than obj-c -> c -> c++ is anyone's guess, probably even less so if you have to maintain the C bindings for other reasons too.
 
Status
Not open for further replies.