Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linker error using extern "C" in Objective-C code

I'm trying to create some utility functions that can be called from both Objective-C and C++ code in an iPhone application. I have third party C++ classes that cannot be compiled as ObjectiveC++ (.mm). I have a header file declaring my functions, then a .c file defining them. I've tripled checked for spelling errors, but for some reason my linker is NOT able to find the definition of any of the functions.

Here is the header for the C helper functions:

#ifndef FILE_LOADER_H
#define FILE_LOADER_H

#if __cplusplus
extern "C" {
#endif

void * loadDataFromFile(const char * szFilename, bool bDocument);
void * loadImageFromFile(const char * szFilename, bool bDocument);
void loadMeshFromFile(const char *szFilename, void* pMesh);

#if __cplusplus
}   // Extern C
#endif

#endif

And here is the .c file:

#include "FileLoader.h"
#include <objc/objc.h>
#include <objc/message.h>
#include <Foundation/Foundation.h>


void * loadDataFromFile(const char * szFilename, bool bDocument)
{
    Class loaderClass = NSClassFromString(@"Loader");
    void * pReturnVal = objc_msgSend(loaderClass,   NSSelectorFromString(@"loadDataFromFile:document"), szFilename, bDocument);
    return pReturnVal;
    //return [Loader loadDataFromFile:szFilename document:bDocument];
}
void * loadImageFromFile(const char * szFilename, bool bDocument)
{
    Class loaderClass = NSClassFromString(@"Loader");
    void * pReturnVal = objc_msgSend(loaderClass, NSSelectorFromString(@"loadImageFromFile:document"), szFilename, bDocument);
    return pReturnVal;
    //return (void*)[Loader loadImageFromFile:szFilename document:bDocument];
}
void loadMeshFromFile(const char *szFilename, void* pMesh)
{
    Class loaderClass = NSClassFromString(@"Loader");
    objc_msgSend(loaderClass, NSSelectorFromString(@"loadMeshFromFile:mesh"), szFilename, pMesh);
    //[Loader loadMeshFromFile:szFilename mesh:pMesh];
}

I've tried compiling with and without the extern "C", but with the same linker error result.

Can anyone shed some light on what I'm doing wrong?

Linker Error:

Undefined symbols for architecture i386:
"loadMeshFromFile(char const*, void*)", referenced from:

UPDATE: I've seemed to solve the problem by compiling my source file as objective C, even though there was no actual ObjectiveC code, can anyone tell me why the above source file won't compile as C code?

like image 322
dewhacker Avatar asked Jan 18 '23 18:01

dewhacker


1 Answers

use the following construct to specify c linkage for c and c++ translations:

#if !defined(__cplusplus)
#define MONExternC extern
#else
#define MONExternC extern "C"
#endif
// declare loadMeshFromFile
MONExternC void loadMeshFromFile(char const*, void*);

this declaration will be compatible with c, objc, c++, objc++.

like image 183
justin Avatar answered Jan 28 '23 16:01

justin