Creating and Using a Simple .dylib

你离开我真会死。 提交于 2019-12-06 06:27:31

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4405243/creating-and-using-a-simple-dylib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!