C编译入门
环境:ubuntu
-
gcc/g++
gcc -o hello.out hello.c //-o表示目标文件 ./hello.out //运行生成hello.out文件,通过 g++ -g -c hw2.cpp // -g为生成文件可调试((通过gdb进行调试),-c:Compile and assemble, but do not link -
makefile指令
target ... : prerequisites ... command #注意前面间隔为tab注意:tab命令行tab一定要手敲,复制可能会因为转码问题导致
makefile:6: *** missing separator. Stop.的问题举例
存在三个文件 /* solution.h */ class Solution { public: void Say();//声明Say()方法 }; /* solution.cpp */ #include <iostream> #include "solution.h" void Solution::Say(){//实现Say()方法 std::cout << "HI!" << std::endl; } /* hw2.cpp */ #include "solution.h" int main () {//主函数,使用Say()语法 Solution sln; sln.Say(); return 0; } 由上可之程序入口为hw2.cpp文件,该文件引用了.h文件,.h文件中的Say()实现位于.c文件中,由此 创建makefile文件在同一文件夹,内容为 build : hw2.o solution.o #目标为build文件,所需资源为hw2.o&solution.o,目标不存在或者资源文件不存在或者更新时执行command命令 g++ -o build hw2.o solution.o hw2.o : hw2.cpp solution.h #在执行g++ -o build hw2.o solution.o 嵌套过程中,该部分的资源文件是齐全的,于是会先执行该语句 g++ -g -c hw2.cpp solution.o : solution.h solution.cpp#同上 g++ -g -c solution.cpp clean : #特殊指令,不生成文件,执行clean语句make clean时会执行以下command rm hw2.o solution.o build -
gdb调试
代码编写结束后,可以使用gdb进行代码的调试,ubuntu环境apt install gdb,以下以c文件编译调试举例gcc -g -o hello hello.c //编译.c文件,生成hello文件,-g参数为可调试 gdb hello //调试hello文件 Reading symbols from hello... (gdb) list //进入gdb模式,打印出代码 1 #include <stdio.h> 2 3 int main() 4 { 5 printf("Hello, World! \n"); 6 7 return 0; 8 } 9 (gdb) break 5 //在第5行添加断点 Breakpoint 1 at 0x1151: file hello.c, line 5. (gdb) r //开始运行 Starting program: /home/chen/c_project/hello warning: Error disabling address space randomization: Operation not permitted Breakpoint 1, main () at hello.c:5 //代码将开始运行并在5行处停止 5 printf("Hello, World! \n"); (gdb) c //c("continue")继续调试 Continuing. Hello, World! //打印 [Inferior 1 (process 27696) exited normally] (gdb) c The program is not being run. //由于后面没有断点了,程序运行结束 (gdb) q //q(quit)退出gdb调试模式
参考
4436

被折叠的 条评论
为什么被折叠?



