How do I use a dynamic shared library in a C++ xcode project?

Alexander Rafferty picture Alexander Rafferty · May 14, 2012 · Viewed 9.6k times · Source

I have created a new project in XCode (using the template "STL C++ library"), and have made a little test function void hello(); that prints to the console.

It compiles fine, and I am able to export a dylib file.

What I can't figure out is how to create a project that then links to this file and can call the hello() method.

Any advice would be greatly appreciated.

Alex.

Answer

Mark Szymczyk picture Mark Szymczyk · May 14, 2012

Create another Xcode project, such as an application project. In your example you could create a command-line tool project that uses C++.

After creating the project add the dylib to the target's Link Binary with Libraries build phase. In Xcode 4, select the project from the project navigator to open the project editor. Select the target from the target list on the left side of the project editor. Click the Build Phases button at the top of the editor. Click the disclosure triangle next to the Link Binary with Libraries build phase. Click the + button to add your library.

When you finish adding the dylib to your project, include the header file for your library in your code, and you should be able to call the hello() function. You may also need to add a search path to your library to the Library Search Paths build setting to use your library.