user277465
user277465

Reputation:

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/

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?

Upvotes: 18

Views: 31819

Answers (2)

linuxbuild
linuxbuild

Reputation: 16133

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

Upvotes: 33

spartygw
spartygw

Reputation: 3462

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

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

Upvotes: 11

Related Questions