14

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?

Janani
  • 201
  • 1
  • 2
  • 11

1 Answers1

36

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);
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 1
    I tried adding extern "c".but i get a new error - "Expected identifier or '(' before string constant" – Janani Dec 16 '10 at 00:19
  • @whocares, you need to add the `extern "C"` only for C++ - that means wrapping it in an `#ifdef __cplusplus` block. – Carl Norum Dec 16 '10 at 00:28
  • 1
    @Carl - Thanks a lot for the response! Linker error is gone now!! but I got a new warning in "test_viewcontroller.m" - implicit declaration of function "donothing()".I believe that this happens only when I have not included the header file which has function declaration.but I have an imported foo.h in "test_viewcontroller.m".Can you please tell me what is wrong? – Janani Dec 16 '10 at 00:36
  • 2
    @whocares, I'm guessing that means your `#ifdef` block is too big. Put *just* the `extern "C"` inside the `#ifdef`, not the whole function declaration. – Carl Norum Dec 16 '10 at 00:37
  • @Carl - Thanks a lot for the detailed reply! works as advertised :) I have registered in Stackoverflow!! – Janani Dec 16 '10 at 01:32
  • 2
    @whocares: and now you need to accept the answer, since it fixes your problem. – JeremyP Dec 16 '10 at 09:38