首先准备编译环境,操作系统为Fedora OS:

yum install gcc g++
yum install glibc-headers

Create hello.h

#ifndef HELLO_H
#define HELLO_H

void hello(const char *name);
#endif

Create >hello.c

#include <stdio.h>

void hello(const char *name)
{
        printf("hello %s!\n",name);
}

Create >main.c

#include "hello.h"

int main(){
        hello("linux");
        return 0;
}

Execute binary

gcc -Wall hello.c main.c
./main

Static Lib

gcc -c hello.c -o hello.o
ar rcs libhello.a hello.o
gcc main.c -o main -static -L. -lhello
./main

Shared Lib

gcc -fPIC -c hello.c -o hello.o
gcc -shared -o libhello.so.1.0.0 hello.o
ln -s libhello.so.1.0.0 libhello.so
gcc main.c -o main -L. -lhello
export LD_LIBRARY_PATH=$(pwd)
./main

Makefile

CC=gcc
CFLAGS=-c
hello:  main.o hello.o
        $(CC) hello.o main.o -o hello
hello.o: hello.c
        $(CC) $(CFLAGS) hello.c -o hello.o
main.o: main.c hello.h
        $(CC) $(CFLAGS) main.c -o main.o
clean:
        rm -rf *.o


blog comments powered by Disqus

Published

18 December 2012

Tags