C/C++多文件目录编译
本人的项目目录如下:
- helloworld
- header
helloworld.h
- src
helloworld.cpp
main.cpp
- bin
a.exe
在编译g++ src/main.cpp src/helloworld.cpp -o bin/a.exe
时控制台error: fatal error: header/helloworld.h: No such file or directory
,源文件是这样#include"header/helloworld.h"
#include<>和#include" "的区别是前者在系统预定义的路径进行查找文件,后者在源文件当前目录为基准进行查找文件,默认在当前文件所在的目录中查找;
所以在编译时系统在src/目录下没有找到header/helloworld.h,因为header目录和src目录是同级目录,src下面根本就没有header目录,
后来更改成了#include "../header/helloworld.h",重新编译时才通过;
并且一般都是#include"相对路径",因为之前我的源文件是#include"header/helloworld.h",所以才找不到头文件,
当然不嫌麻烦写成绝对路径也可以进行编译,但是绝对路径本身就很繁琐。
-I 选项用于添加头文件搜索路径,例如:
g++ src/main.cpp src/helloworld.cpp -o bin/a.exe -I header/
基于当前工作目录(执行g++的目录),把当前目录下的header目录加入头文件搜索路径,因此源文件可以这样#include"helloworld.h"
-o 选项用于指定输出文件的名称;
-E 预编译,对源代码进行预处理,生成xx.i文件,例如:g++ -E main.cpp -o main.i
;
-S 编译,把预处理的xx.i文件编译成汇编文件,生成xx.s文件,例如:g++ -S main.i -o main.s || g++ -S main.cpp -o main.s
;
-c 汇编,汇编代码转换为机器代码,不链接,生成xx.o文件,例如:g++ -c main.s -o main.o || g++ -c main.cpp -o main.o
;
链接,不带指令,例如:`g++ main.o -o main.exe(main) || g++ main.cpp file1.cpp file2.cpp -o main.exe(main);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构