linux项目_c语言:Makefile编写、动态库生成、添加动态库路径

一直想搞懂Linux中Makefile是怎么管理项目的,知识积累到一定程度后,我就做了一个自己的缩小项目去把剩下的细节搞清楚

代码:

Service.c:

c 复制代码
#include <stdio.h>
#include "lib_sevr.h"
int main(){

    printf("输入a, b的值:\n");
    double a, b;
    scanf("%lf %lf", &a, &b);
    printf("%lf + %lf = %.1f\n", a, b, add(a, b));
    return 0;
}

lib_sevr.c:

c 复制代码
#include "lib_sevr.h"

double add(double a, double b){
    return a + b;
}

lib_sevr.h:

c 复制代码
#ifndef __LIB_SEVR__H__
#define __LIB_SEVR__H__

double add(double a, double b);

#endif  //!__LIB_SEVR__H__

项目.c文件的大致位置关系是这样的:

编译涉及到路径问题

复制代码
gcc -fpic -shared -I../Client/ lib_sevr.c -o libsevr.so 
# 生成与路径无关的动态库,-I是指定头文件路径
vi /etc/profile
export LD_LIBRARY_PATH=/home/saisi/Desktop/Cproject/Server/
# 进入配置.so动态库的环境变量路径
source /etc/profile
#读取路径
#最好再重启一下,因为读取是只对本终端有效,退出后又要重新读取

因为动态库并不是写入可执行程序里的,可执行程序里只有动态库的链接,加载器在执行到相应位置后得通过这些环境变量找到动态库路径

复制代码
gcc -o main -I../Client/ Server.c libsevr.so
# 将动态库链接到主函数,并生成可执行文件,-I仍是指定.h文件位置

可以执行,那么将上述编译操作写到Makefile文件中即可

bash 复制代码
# ~/Desktop/Cproject$ 
all:
	$(MAKE) -C Server

clean:
	rm -f ./Server/main ./Server/*.so
bash 复制代码
#~/Desktop/Cproject/Server$ 
all: MAIN

MAIN: Server.c libsevr.so
	gcc -o main -I../Client/ Server.c libsevr.so

libsevr.so: lib_sevr.c
	gcc -fpic -shared -I../Client/ lib_sevr.c -o libsevr.so 

当然还Makefile可以再优化

相关推荐
Full Stack Developme1 小时前
Linux 多种压缩格式,优缺点和适用场景
linux·运维·服务器
旖旎夜光1 小时前
Linux(4)(下)
linux·学习
yBmZlQzJ6 小时前
财运到内网穿透域名解析技术机制与中立评估
运维·经验分享·docker·容器·1024程序员节
Shanxun Liao6 小时前
Cenots 7.9 配置多台 SSH 互信登陆免密码
linux·运维·ssh
j_xxx404_6 小时前
Linux:第一个程序--进度条|区分回车与换行|行缓冲区|进度条代码两个版本|代码测试与优化
linux·运维·服务器
一点晖光6 小时前
jenkins优化记录
运维·jenkins
looking_for__6 小时前
【Linux】Ext系列文件系统
linux
最贪吃的虎7 小时前
Git: rebase vs merge
java·运维·git·后端·mysql
OliverH-yishuihan7 小时前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
yBmZlQzJ7 小时前
内网穿透工具通过端口转发实现内外网通信
运维·经验分享·docker·容器·1024程序员节