关于静态库和动态库的链接

来源:互联网 发布:php mongodb remove 编辑:程序博客网 时间:2024/06/17 12:23

static1.cpp
#include <stdio.h>void f(){    printf("static1::f()\n");}
static2.cpp
#include <stdio.h>void f(){    printf("static2::f()\n");}
main.cpp
#include <stdio.h>extern void f();int main(){    f();    return 0;}
ar -rs libstatic1.a static1.o
ar -rs libstatic2.a static2.o

g++ main.o ./libstatic1.a ./libstatic2.a -o main

./main

static1::f()

g++ main.o ./libstatic2.a ./libstatic1.a -o main

./main

static2::f()

ar -rs libstatic.a static2.o static1.o 

g++ main.o ./libstatic.a -o main

./main

static2::f()

ar -rs libstatic.a static1.o static2.o 

g++ main.o ./libstatic.a -o main

./main

static1::f()


export LD_LIBRARY_PATH=./

g++ -c -fPIC static1.cpp

g++ -shared -fPIC -o libstatic1.so static1.o

g++ -o main main.cpp -L. -lstatic1

./main

static1::f()

g++ -c -fPIC static2.cpp

g++ -shared -fPIC -o libstatic2.so static2.o

g++ -o main main.cpp -L. -lstatic2

./main

static2::f()

g++ -o main main.cpp -L. -lstatic1 -lstatic2

./main

static1::f()
</pre>g++ -o main main.cpp -L. -lstatic2 -lstatic1<p></p><p>./main</p><p></p><pre code_snippet_id="1940170" snippet_file_name="blog_20161020_9_6832265" name="code" class="cpp">static2::f()

jfk@ubuntu:~/code/link$ g++ -shared -fPIC -o libstatic.so static2.o static1.o  
static1.o: In function `f()':
static1.cpp:(.text+0x0): multiple definition of `f()'
static2.o:static2.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status


g++ -L. -lstatic1 main.cpp -o main

/tmp/ccfEWFaN.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `f()'
collect2: error: ld returned 1 exit status


g++ -L. main.cpp -o main -lstatic1

./main

static1::f()


g++ static1.o main.cpp -o main

./main 

static1::f()


g++ main.cpp -o main static1.o

./main 

static1::f()






如下关于链接的说法错误的是()

A、一个静态库中不能包含两个同名全局函数的定义

B、一个动态库中不能包含两个同名全局函数的定义

C、如果两个静态库都包含一个同名全局函数,他们不能同时被链接

D、如果两个动态库都包含一个同名全局函数,他们不能同时被链接


0 0
原创粉丝点击