动态库链接静态库示例

来源:互联网 发布:热血战歌涅盘数据 编辑:程序博客网 时间:2024/05/21 17:58

实验场景说明:

程序链接动态库,动态库链接静态库

(没看到怎么插入c++代码,插入c#代替吧)

staticlib.h

 

#ifndef _STATIC_LIB_H_
#define _STATIC_LIB_H_

#include 
<stdio.h>

void sf();

#endif

 

staticlib.cpp

 

#include "staticlib.h"

void sf()
{
    printf(
"func in static lib ");
}

 

dynamic.h

 

#ifndef _DYNAMIC_LIB_H_
#define _DYNAMIC_LIB_H_

#include 
<stdio.h>

void df();

#endif

 

dynamic.cpp

 

#include "dynamiclib.h"
#include 
"staticlib.h"

void df()
{
    printf(
"func in dynamic lib ");
    sf();
}

 

test.cpp

 

#include "dynamiclib.h"

int main()
{
    df();
}

 

手工编写的makefile

 

all: static dynamic test

test:test.o
    g
++ -I./ -L./ -L/usr/local/lib -ldynamic test.o -o test

static: staticlib.o
    ar 
-r libstatic.a staticlib.o

dynamic: dynamiclib.o
    g
++ dynamiclib.cpp -o libdynamic.so -fPIC -shared

 

make到最后报错,会说动态库链接不到sf

nm libdynamic.so 会发现sf的符号链接没有找到

按下面方式修改其中一处就可编译通过

dynamic: dynamiclib.o
    g++ dynamiclib.cpp -o libdynamic.so -fPIC -shared -L. -lstatic

或者

test:test.o
    g++ -I./ -L./ -L/usr/local/lib -ldynamic test.o -o test -lstatic

这说明动态库链接静态库,可以在生成动态库的时候就链接进去,也可以到生成可执行文件时再链接

 

用autoconf和automake犯了个错误,在此记下

configure.in

#                                               -*- Autoconf -*-
# Process 
this file with autoconf to produce a configure script.

AC_PREREQ(
2.59)
AC_INIT(FULL
-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
AM_INIT_AUTOMAKE(test, 
1.0)

# Checks 
for programs.
AC_PROG_CXX
AC_PROG_CC
AC_PROG_INSTALL
AC_PROG_RANLIB
AC_PROG_LIBTOOL

# Checks 
for libraries.

# Checks 
for header files.

# Checks 
for typedefs, structures, and compiler characteristics.

# Checks 
for library functions.
AC_OUTPUT(Makefile)

 

Mafile.am

 

AUTOMAKE_OPTIONS=foreign
bin_PROGRAMS
=test
noinst_LIBRARIES
=libstatic.a
lib_LTLIBRARIES
=libdynamic.la

test_SOURCES    
= test.cpp
libstatic_a_SOURCES 
= staticlib.cpp
libdynamic_la_SOURCES
= dynamiclib.cpp

CXXFLAGS
=-D__LINUX__ 

CC
=g++
libdynamic_la_LIBADD
= -L. -lstatic #此处不是 LDADD
test_LDADD
= -L. -ldynamic

 

然后

libtoolize --force
aclocal
autoconf
automake -a
./configure
make

可以在.libs/下面找到生成的东东

 
原创粉丝点击