简体   繁体   中英

Creating shared libraries in C++ for OSX

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(ie 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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM