Creating shared libraries in C++ for OSX

会有一股神秘感。 提交于 2019-11-30 01:38:55

问题


I just started programming in C++ and I've realized that I've been having to write the same code over and over again(mostly utility functions).

So, I'm trying to create a shared library and install it in PATH so that I could use the utility functions whenever I needed to.

Here's what I've done so far :-

Create a file utils.h with the following contents :-

#include<iostream>
#include<string>
std::string to_binary(int x);

Create a file utils.cpp with the following contents :-

#include "utils.h"

std::string to_binary(int x) {
  std::string binary = "";
  while ( x > 0 ) {
    if ( x & 1 ) binary += "1";
    else binary += "0";
    x >>= 1;
  }
  return binary;
}

Follow the steps mentioned here :- http://www.techytalk.info/c-cplusplus-library-programming-on-linux-part-two-dynamic-libraries/

  • Create the library object code : g++ -Wall -fPIC -c utils.cpp

But as the link above is meant for Linux it does not really work on OSX. Could someone suggest reading resources or suggest hints in how I could go about compiling and setting those objects in the path on an OSX machine?

Also, I'm guessing that there should be a way I can make this cross-platform(i.e. write a set of instructions(bash script) or a Makefile) so that I could use to compile this easily across platforms. Any hints on that?


回答1:


Use -dynamiclib option to compile a dynamic library on OS X:

g++ -dynamiclib -o libutils.dylib utils.cpp

And then use it in your client application:

g++ client.cpp -L/dir/ -lutils



回答2:


The link you posted is using C and the C compiler. Since you are building C++:

g++ -shared -o libYourLibraryName.so utils.o


来源:https://stackoverflow.com/questions/14173260/creating-shared-libraries-in-c-for-osx

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