Makefile:静态库与动态库:修订间差异

来自WHY42
imported>Soleverlee
(以“<source lang="make" highlight="15-19"> CC = gcc COMPILER_FLAGS = -O2 objects = mathApi.o main.o bin = hello.exe static = libmath.a shared = libmath.so all:main m...”为内容创建页面)
 
imported>Soleverlee
无编辑摘要
 
第25行: 第25行:
</source>
</source>


=C/C++混合编程=
在C和C++混用的情况下,因为导出符号不同,链接时需要注意,有两种做法让C和C++兼容:
<source lang="cpp">
//test.cpp
extern "C"{
#include "mathApi.h"
}
</source>
或者直接在头文件中进行处理:
<source lang="cpp">
//mathApi.h
#ifdef __cplusplus
extern "C"{
#endif
//....
#ifdef __cplusplus
}
#endif
</source>
可以试用nm命令查看导出函数:
<source lang="bash">
nm libmathApi.a
</source>
另外,遇到个蛋疼的问题,无论如何编译都提示: Undefined reference to..,后来发现,-l选项必须放在源文件后面:
<source lang="bash">
#wrong
#g++ -o test.exe -I. -L. -lmathApi test.cpp
g++ -o test.exe -I. -L. test.cpp -lmathApi
</source>
[[Category:Programe]]
[[Category:Programe]]

2016年6月10日 (五) 02:52的最新版本

CC = gcc

COMPILER_FLAGS = -O2

objects = mathApi.o main.o
bin = hello.exe
static = libmath.a
shared = libmath.so

all:main

main:$(objects)
        $(CC) -o $(bin) $(objects)

static:mathApi.o
        ar cr $(static) mathApi.o

shared:mathApi.o
        $(CC) $(COMPILER_FLAG) mathApi.o -shared -fPIC -o $(shared)

.PHONY: clean
clean:
        rm -f $(objects) $(bin)

C/C++混合编程

在C和C++混用的情况下,因为导出符号不同,链接时需要注意,有两种做法让C和C++兼容:

//test.cpp
extern "C"{
#include "mathApi.h"
}

或者直接在头文件中进行处理:

//mathApi.h
#ifdef __cplusplus
extern "C"{
#endif

//....

#ifdef __cplusplus
}
#endif

可以试用nm命令查看导出函数:

nm libmathApi.a

另外,遇到个蛋疼的问题,无论如何编译都提示: Undefined reference to..,后来发现,-l选项必须放在源文件后面:

#wrong
#g++ -o test.exe -I. -L. -lmathApi test.cpp 
g++ -o test.exe -I. -L. test.cpp -lmathApi