2016年7月18日 星期一

C/C++指針

c language creates dynamic library .a in linux

Create source code

1. input source code

a) [projectFolder]/src/header/hello.h


#ifndef HELLO_H
#define HELLO_H

void hello(const char *name);

#endif

b) [projectFolder]/src/hello.c


#include

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

2. compile library source code to object file

cd [projectFolder]
 gcc -c -fPIC src/hello.c -o debug/hello.o

3. package object files to dynamic library

 gcc -shared -fPIC -o bin/libhello.so debug/hello.o



Using dynamic library 

1. input source code

a) [projectFolder]/src/main.c

#include "hello.h"

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

2. copy header files *.h to [projectFolder]/src/header

3. copy dynamic library libhello.so to [projectFolder]/dlib

4. compile source code with header files and dynamic libraries .so

 gcc -o bin/hello src/main.c -I./src/header -L./dlib -lhello

5. run program

cp [projectFolder]/dlib/libhello.so /usr/lib
./bin/hello

c language creates static library .a in linux

Create source code

1. input source code

a) [projectFolder]/src/header/hello.h


#ifndef HELLO_H
#define HELLO_H

void hello(const char *name);

#endif

b) [projectFolder]/src/hello.c


#include

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

2. compile library source code to object file

cd [projectFolder]
gcc -c src/hello.c -o debug/hello.o

3. package object files to static library

ar rcs bin/libhello.a debug/hello.o



Using static library 

1. input source code

a) [projectFolder]/src/main.c

#include "hello.h"

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

2. copy header files *.h to [projectFolder]/src/header

3. copy static library libhello.a to [projectFolder]/lib

4. compile source code with header files and static libraries

gcc -o bin/hello src/main.c -I./src/header -L./lib -lhello

5. run program

./bin/hello