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可以再优化

相关推荐
少妇的美梦13 小时前
logstash教程
运维
chen94514 小时前
k8s集群部署vector日志采集器
运维
chen94514 小时前
aws ec2部署harbor,使用s3存储
运维
轻松Ai享生活18 小时前
5 节课深入学习Linux Cgroups
linux
christine-rr19 小时前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神55519 小时前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆19 小时前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
qq_2642208919 小时前
LVS负载均衡群集和LVS+Keepalived群集
运维·负载均衡·lvs
乌萨奇也要立志学C++19 小时前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
雨落Liy19 小时前
Nginx 从入门到进阶:反向代理、负载均衡与高性能实战指南
运维·nginx·负载均衡