Maxpm
Maxpm

Reputation: 25612

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.

Upvotes: 3

Views: 8216

Answers (2)

lucas clemente
lucas clemente

Reputation: 6409

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.

Upvotes: 2

Yttrill
Yttrill

Reputation: 4931

FWIW my production compiler uses this:

/usr/bin/g++ -c -fno-common -fPIC   -Wall \
-Wno-invalid-offsetof -Wfatal-errors -fPIC \
-O3 -fomit-frame-pointer --inline  -DTARGET_BUILD \
-I/usr/local/lib/felix/felix-1.1.6rc1/lib/rtl \
-I/usr/local/lib/felix/felix-1.1.6rc1/config/target \
./hello.cpp -o ./hello.os

/usr/bin/g++ -fno-common -dynamiclib   -O3 \
-fomit-frame-pointer --inline   \
./hello.os -o ./hello.dylib \
-L/usr/local/lib/felix/felix-1.1.6rc1/lib/rtl \
-lflx_dynamic -lflx_gc_dynamic -lflx_judy_dynamic -lflx_exceptions_dynamic

to make hello.dylib from hello.cpp, you can strip out the non-essential bits, which are in there just because that's what is in there in my system and might help if you want to do a bit more advanced stuff later. The -fPIC in the compile is mandatory. The -dynamiclib is what makes the dylib.

Upvotes: 0

Related Questions