User Tools

Site Tools


user:afassett:hpc_ii:c_static_liberaries

using/linking libraries with your C/C++ programs

Objectives

The goal here is to make static libraries, which makes coding easier. With libraries you can now reuse code and implement old code into new code. What else could be greater?

Materials

  • The ability to learn

Background

From what I have learned proper Makefiles are key, if your compiling yourself it is less likely to have errors since you will know why/what you are missing however using Makefiles will make the process much quicker and easier for you to use.

Procedures

File libhello.c is a trivial library, with libhello.h as its header. File demo_use.c is a trivial caller of the library. This is followed by commented scripts (script_static and script_dynamic) showing how to use the library as a static and shared library. This is followed by demo_dynamic.c and script_dynamic, which show how to use the shared library as a dynamically loaded library. 1. File libhello.c- demonstrate library use. */

#include <stdio.h>

void hello(void) {
  printf("Hello, library world.\n");
}

2. File libhello.h- demonstrate library use. */

void hello(void);

3. File demo_use.c- demonstrate direct use of the “hello” routine */

#include "libhello.h"

int main(void) {
 hello();
 return 0;
}

4. File script_static

#!/bin/sh
# Static library demo

# Create static library's object file, libhello-static.o.
# I'm using the name libhello-static to clearly
# differentiate the static library from the
# dynamic library examples, but you don't need to use
# "-static" in the names of your
# object files or static libraries.

gcc -Wall -g -c -o libhello-static.o libhello.c

# Create static library.

ar rcs libhello-static.a libhello-static.o

# At this point we could just copy libhello-static.a
# somewhere else to use it.
# For demo purposes, we'll just keep the library
# in the current directory.

# Compile demo_use program file.

gcc -Wall -g -c demo_use.c -o demo_use.o

# Create demo_use program; -L. causes "." to be searched during
# creation of the program.  Note that this command causes
# the relevant object file in libhello-static.a to be
# incorporated into file demo_use_static.

gcc -g -o demo_use_static demo_use.o -L. -lhello-static

# Execute the program.

./demo_use_static

References

user/afassett/hpc_ii/c_static_liberaries.txt · Last modified: 2011/05/13 01:21 by afassett