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.