Skip to Main Content
Mac OS X for Unix Geeks
book

Mac OS X for Unix Geeks

by Ernest E. Rothman, Brian Jepson
September 2002
Beginner to intermediate content levelBeginner to intermediate
216 pages
7h 43m
English
O'Reilly Media, Inc.
Content preview from Mac OS X for Unix Geeks

Building a Shared Library

Suppose you want to create a shared library containing one or more C functions, such as the one shown in Example 5-3.

Example 5-3. A simple C program
/*
 * answer.c: The answer to life, the universe, and everything.
 */
int get_answer(  ) 
{
  return 42;
}

If you compile the program containing the function into a shared library, you could test it with the program shown in Example 5-4.

Example 5-4. Compiling answer.c into a shared library
/*
 * deep_thought.c: Obtain the answer to life, the universe, 
 * and everything, and act startled when you actually hear it.
 */
#include <stdio.h>
int main(  )
{
  int the_answer;
  the_answer = get_answer(  );
  printf("The answer is... %d\n", the_answer);

  fprintf(stderr, "%d??!!\n", the_answer);
  return 0;
}

The makefile shown in Example 5-5 will compile and link the library, and then compile, link, and execute the test program.

Example 5-5. Sample makefile for creating and testing a shared library
# Makefile: Create and test a shared library. # # Usage: make test # CC = cc LD = cc CFLAGS = -O -fno-common all: deep_thought # Create the shared library. # answer.o: answer.c $(CC) $(CFLAGS) -c answer.c libanswer.dylib: answer.o $(LD) -dynamiclib -install_name libanswer.dylib \ -o libanswer.dylib answer.o # Test the shared library with the deep_thought program. # deep_thought.o: deep_thought.c $(CC) $(CFLAGS) -c deep_thought.c deep_thought: deep_thought.o libanswer.dylib $(LD) -o deep_thought deep_thought.o -L. -lanswer test: all ./deep_thought ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mac OS X For Unix Geeks, 4th Edition

Mac OS X For Unix Geeks, 4th Edition

Ernest E. Rothman, Rich Rosen, Brian Jepson
Mac OS X Hacks

Mac OS X Hacks

Kevin Hemenway, Rael Dornfest
Mac OS X in a Nutshell

Mac OS X in a Nutshell

Jason McIntosh, Chuck Toporek, Chris Stone

Publisher Resources

ISBN: 0596003560Errata Page