c++dylibdynamic-library

Creating and Using a Simple .dylib


What's the most basic way to create and use a .dylib in Xcode?

Here's what I have so far:

File: MyLib.h

#include <string>

namespace MyLib
{
    void SayHello(std::string Name);
}

File: MyLib.cpp

#include <string>
#include <iostream>

#include "MyLib.h"

void MyLib::SayHello(std::string Name)
{
    std::cout << "Hello, " << Name << "!";
}

I got the project to compile as a dynamic library, but how do I use it with other projects? I tried something like this:

File: MyLibTester.cpp

#include "libMyLib.dylib"

int main()
{
    MyLib::SayHello("world");
    return 0;
}

But that gave me over 400 errors (mostly along the lines of Stray \123 in program. Using <libMyLib.dylib> gave me a file not found error.


Solution

  • You don't include the library file, but the header (.h)

    So write

    #include "MyLib.h"

    You then have to tell the compiler for your program to link against the dylib file. If you are using Xcode you can simply drag the dylib file into your project.