我理解中,.so文件就相当于windows下的.dll文件。 环境不一样,感觉就不一样。 windows下的.dll文件虽然做了好些,但是怎么用makefile写还是不怎么了解。到了linux下更是完全扯着蛋了。

随便写了个so文件的sample。如有误,看官请指出。

tomato.c生成动态链接库.

#include <string.h>
#include <stdio.h>

int tomato(char *str)
{
    printf("[so] : tomato called ~ \n");
    sprintf(str,"writen by tomato \n");
    return 1;
}

test.c调用tomato.c中tomato方法

#include <stdio.h>
int main()
{
    char aa[200];
    printf("[call tomato] : %d\n",tomato(aa));
    printf("[result] : %s \n",aa);
    return 0;
}

写个makefile来生成文件.

CC       := gcc
CFLAGS   := -Wall #-std=c99
SHARED   := -shared -fPIC
FRUITLIB := `pwd`  -lfruit
LIBS     := -L
LIBS     += ${FRUITLIB}

TSTOBJ   := test.o

PROGS    := libfruit.so test

#---------------------------------------------------------------------

.PHONY   : all rebuild clean  run
all      : ${PROGS} succ

rebuild  : clean all

test     : ${TSTOBJ}
    ${CC} ${CFLAGS} -o $@ ${TSTOBJ} ${LIBS}

#test.o   : libfruit.so
#   ${CC} ${CFLAGS} -o $@ test.c ${LIBS}

libfruit.so : ${FROBJ}
    ${CC} ${CFLAGS} -o $@ tomato.c ${SHARED}

run      : test
    @echo "have a show :"
    LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. ./test

succ     :
    @echo "Complete !"

clean    :
    -rm -f ${PROGS} ${TSTOBJ} ${FROBJ}
    -rm -f *~
    -rm -f *.swp

输出如下:

[yu@argcv-com fruit]$ make clean
rm -f libfruit.so test test.o
rm -f *~
rm -f *.swp
[yu@argcandargv-com fruit]$ make
gcc -Wall  -o libfruit.so tomato.c -shared -fPIC
gcc -Wall    -c -o test.o test.c
test.c: In function ‘main’:
test.c:5:2: warning: implicit declaration of function ‘tomato’ [-Wimplicit-function-declaration]
gcc -Wall  -o test test.o -L `pwd`  -lfruit
Complete !
[yu@argcandargv-com fruit]$ make run
have a show :
LD_LIBRARY_PATH=. ./test
[so] : tomato called ~
[call tomato] : 1
[result] : writen by tomato

"implicit declaration of function" ? 参考 这篇.

注意,本文只是强行介绍了一下怎么调用.so中的内容.一般情况是不太会这么做的.一个很重要的是,头文件.我们会写一个头文件如下

#ifndef TOMATO_H
#define TOMATO_H

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus

int tomato(char *str);

#ifdef __cplusplus
}
#endif  // __cplusplus

#endif  //  TOMATO_H

然后tomato.c和test.c中都加一句

#include "tomato.h"

这样就可以保证接口没问题,消除warning了.

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

Leave a Reply

Your email address will not be published. Required fields are marked *