c++swiftxcodeg++objective-c-swift-bridge

Error to compile Xcode Swift project using C++ library linked on Build Phases


I've searched a lot on the web but not found the solution for my problem. My objective is create a simple class in C++ and use it on Swift. To this I did follows this tutorial -> http://www.swiftprogrammer.info/swift_call_cpp.html (It's very nice). Basically I've followed the steps:

  1. Create junk.cpp and junk.h files
  2. Compile using g++ or/and clang++
  3. Create .a file with: $ ar r libjunkcpp.a junk.o
  4. Linked to Xcode in Build Phases -> Link Binary With Libraries -> Add

So when I did this the Xcode not compiles more my project, on the left side of Xcode appears the error message:

linker command failed with exit code 1 (use -v to see invocation)

And on the log the error's message is:

ld: archive has no table of contents file '/Users/augustosansoncadini/Documents/XcodeProjects/Ex_cpp_Swift_CmdLineTool/junk/libjunkcpp.a' for architecture x86_64

I think that need compile to it architecture but when I type g++ -v the result is:

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.11.45.5)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

So I conclude that the architecture target is correct.

I think that this image can help:

enter image description here

Note: When I remove .a file from Link Binary With Libraries the code compiles fine.


Solution

  • What you miss is a call to the ranlib command to generate the table of contents:

    $ ranlib libjunkcpp.a
    

    The ar and ranlib commands must always be paired.