Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

iphone - Calling C++ method from Objective C

I have the following files.

foo.h (C++ header file)
foo.mm (C++ file)
test_viewcontroller.h (objective c header file)
test_viewcontroller.m (Objective c file)

I have declared a method donothing() in foo.h and defined it in foo.mm.Lets say it is

double donothing(double a) { return a; }

Now,I try to call this function in test_viewcontroller.m

double var = donothing(somevar);

I get linker error which says "cannot find symbols" _donothing() in test_viewcontroller.o
collect2: ld returned 1 exit status

Can anyone please point me as to what is wrong?


Let me be precise :

#ifdef __cplusplus 

extern "C" 
{
      char UTMLetterDesignator(double Lat);
      NSString * LLtoUTM(double Lat,double Long,double UTMNorthing, double UTMEasting);
      double test(double a);
}

#endif

@Carl

I have included my code sample.Are saying that I need to wrap only the test() method in ifdef.I dont understand what difference it can make.Can you please explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

test_viewcontroller.m is looking for a non-C++-mangled symbol name for donothing(). Change its extension to .mm and you should be good. Alternately, put an extern "C" declaration on your method declaration in foo.h when compiling the C++ file.

You want to have it look like this:

foo.h:

#ifdef __cplusplus
extern "C" {
#endif

double donothing(double a);

#ifdef __cplusplus
}
#endif

foo.mm:

#include "foo.h"

double donothing(double a)
{
    return a;
}

test_viewcontroller.m:

#import "foo.h"

- (double)myObjectiveCMethod:(double)x
{
    return donothing(x);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...