Augusto
Augusto

Reputation: 4243

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.

Upvotes: 0

Views: 528

Answers (2)

andreyb
andreyb

Reputation: 41

Had a similar problem by the end of the same tutorial at http://www.swiftprogrammer.info/swift_call_cpp.html.

But the error I got when building the project was:

ld: library not found for -ljunkcpp
clang: error: linker command failed with exit code 1 (use -v to see invocation)

No idea where the "ljunkcpp" naming (vs "libjunkcpp") suddenly came from, but what I did to solve it was:

  1. Removed libjunkcpp.a altogether.
  2. Compiled with g++ -c junk.cpp again.
  3. Ran ar r hellocpp.a junk.o again (notice the different hellocpp.a filename).
  4. Removed the old Build Phase Link to libjunkcpp.a.
  5. Linked hellocpp.a instead in Link Binary With Libraries. Rebuilt and ran.
Hello, World!
The integer from C++ is 1234

Must have been some name collision. Hope this helps someone.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409432

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.

Upvotes: 1

Related Questions