如何在linux中使用Makefile构建一个C++工程?

环境为Fedora41,gcc 版本 14.2.1 20250110 (Red Hat 14.2.1-7) (GCC)

步骤1:安装必要的工具

首先确保系统已安装C++编译器和构建工具:

bash 复制代码
sudo dnf install gcc-c++ make

步骤2:创建工程目录结构

bash 复制代码
# 创建工程目录
mkdir cpp_project
cd cpp_project

# 创建源代码目录和构建目录
mkdir src build include

# 创建源代码文件
touch src/main.cpp
touch include/hello.h
touch src/hello.cpp

步骤3:编写代码

使用文本编辑器(如nano或vim)编写以下文件:

  1. include/hello.h 头文件:
cpp 复制代码
#ifndef HELLO_H
#define HELLO_H

void print_hello();

#endif
  1. src/hello.cpp 实现文件:
cpp 复制代码
#include <iostream>
#include "hello.h"

void print_hello() {
    std::cout << "Hello from C++ project!" << std::endl;
}
  1. src/main.cpp 主程序文件:
cpp 复制代码
#include "hello.h"

int main() {
    print_hello();
    return 0;
}
  1. 创建Makefile:
bash 复制代码
touch Makefile

编辑Makefile内容:

bash 复制代码
# 编译器设置
CXX = g++
CXXFLAGS = -std=c++11 -Iinclude -Wall

# 目标文件和可执行文件
TARGET = build/app
SRCS = src/main.cpp src/hello.cpp
OBJS = $(SRCS:.cpp=.o)

# 默认目标
all: $(TARGET)

# 链接
$(TARGET): $(OBJS)
	$(CXX) $(CXXFLAGS) -o $@ $(OBJS)

# 编译
%.o: %.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

# 清理
clean:
	rm -f $(OBJS) $(TARGET)

# 运行
run: $(TARGET)
	./$(TARGET)

步骤4:编译和运行工程

bash 复制代码
# 编译工程
make
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/a6f8bb0335704f6ea799e9ca92e137c5.png)

# 运行程序
make run

# 如果需要清理编译产物
# make clean

运行后,你应该能看到输出:

复制代码
Hello from C++ project!

工程结构说明

  • src/:存放所有源代码文件(.cpp)
  • include/:存放所有头文件(.h)
  • build/:存放编译生成的可执行文件
  • Makefile:用于自动化编译过程的脚本

这个结构适合小型到中型的C++项目,通过Makefile可以轻松管理编译过程,而不需要每次手动输入长长的编译命令。如果项目规模更大,可以考虑使用CMake等更强大的构建系统。

相关推荐
xu_yule1 小时前
Linux_12(进程信号)内核态和用户态+处理信号+不可重入函数+volatile
linux·运维·服务器
虾..1 小时前
Linux 环境变量&&进程优先级
linux·运维·服务器
i***t9191 小时前
Linux下MySQL的简单使用
linux·mysql·adb
偶像你挑的噻1 小时前
11-Linux驱动开发-I2C子系统–mpu6050简单数据透传驱动
linux·驱动开发·stm32·嵌入式硬件
稚辉君.MCA_P8_Java2 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
凌康ACG2 小时前
Sciter之c++与前端交互(五)
c++·sciter
数据库学啊3 小时前
团队小希望运维简单,时序数据库选型有什么推荐?
运维·数据库·时序数据库
霍格沃兹软件测试开发3 小时前
Playwright MCP浏览器自动化指南:让AI精准理解你的命令
运维·人工智能·自动化
郝学胜-神的一滴4 小时前
Linux命名管道:创建与原理详解
linux·运维·服务器·开发语言·c++·程序人生·个人开发
宾有为4 小时前
【Linux】Linux 常用指令
linux·服务器·ssh