0

In my iOS project, I want to call C++ code from my Swift code.

So, following this tutorial and adding a little bit more stuff, here is what I did:

  • I create the NativeLibWrapper.h file:
#import <Foundation/Foundation.h>

@interface NativeLibWrapper : NSObject

- (NSString *) sayHello: (bool) boolTest;

@end

  • I create the NativeLibWrapper.mm file:
#import <Foundation/Foundation.h>

#import "NativeLibWrapper.h"
#import "NativeLib.cpp"

@implementation NativeLibWrapper

- (NSString *) sayHello: (bool) boolTest {
    NativeLib nativeLib;
    std::string retour = nativeLib.sayHello(boolTest);
    return [NSString stringWithCString: retour.c_str() encoding: NSUTF8StringEncoding];
}

@end
  • I create the NativeLib.hpp file:

#ifndef NativeLib_hpp
#define NativeLib_hpp

#include <stdio.h>
#include <string>

class NativeLib
{
public:
    std::string sayHello(bool boolTest);
};

#endif /* NativeLib_hpp */

  • I create the NativeLib.cpp file:
#include "NativeLib.hpp"

std::string NativeLib::sayHello(bool boolTest)
{
    return "Hello C++ : " + std::to_string(boolTest);
}
  • I add the following in Runner/Runner/Runner-Bridging-Header.h:
#import "NativeLibWrapper.h"
  • And finally, I call the C++ function in Swift:
NativeLibWrapper().sayHello(true)

But if I compile that code, I have the following error:

duplicate symbol 'NativeLib::sayHello(bool)' in:
        /Users/mreg/Library/Developer/Xcode/DerivedData/Runner-behadtvychvlasailnoaimvxgbwa/Build/Intermediates.noindex/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/NativeLib.o
        /Users/mreg/Library/Developer/Xcode/DerivedData/Runner-behadtvychvlasailnoaimvxgbwa/Build/Intermediates.noindex/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/NativeLibWrapper.o
    ld: 1 duplicate symbol for architecture arm64

After some research, I found out that, if I change the NativeLib.cpp content with:

#include "NativeLib.hpp"

std::string NativeLib::sayHello(bool boolTest)
{
    return "Hello C++"; // + std::to_string(boolTest);
}

now, it compiles and works, which is... weird.

So what can I do to get rid of this error, while keeping the original content of NativeLib.cpp?

Thanks.

matteoh
  • 2,810
  • 2
  • 29
  • 54
  • 1
    NativeLibWrapper.mm should import "NativeLib.hpp", not "NativeLib.cpp" – Martin R Feb 19 '22 at 12:03
  • 1
    See for example https://stackoverflow.com/a/28345794/1187415 – Martin R Feb 19 '22 at 12:05
  • Thanks all, that was the right answer! You can post the answer so I will accept it, if you want ;) – matteoh Feb 19 '22 at 12:06
  • Btw, it is correctly described in the tutorial. – Martin R Feb 19 '22 at 12:07
  • Well, it seems that this has been asked and answered several times already, here is another one: https://stackoverflow.com/q/52062179/1187415. My suggestion would be to close this as a duplicate or delete the question. – Martin R Feb 19 '22 at 12:10

0 Answers0