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 :-

  • 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?

2

2 Answers

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
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest