120 likes | 271 Views
实验 1 Linux 下 C 语言程序的编译. 计算机学院 潘薇 panwei117@qq.com. 实验内容. 编写一个 C 程序,完成带参数输入计算 f(x, y)=pow(x, y)+2 ,并在 Linux 下编译生成可执行文件,并进行测试。 要求: 完成 f.c ,其中要实现 f 函数; a.c 中实现 main 函数,对 f 函数进行调用; 编译生成文件 test ; 通过 3 组以上值测试是否正确。. Linux 下的编译工具 ——gcc. 语法: gcc [ 选项 ] 文件列表
E N D
实验1 Linux下C语言程序的编译 计算机学院 潘薇 panwei117@qq.com
实验内容 • 编写一个C程序,完成带参数输入计算f(x, y)=pow(x, y)+2,并在Linux下编译生成可执行文件,并进行测试。 • 要求: • 完成f.c,其中要实现f函数; • a.c中实现main函数,对f函数进行调用; • 编译生成文件test; • 通过3组以上值测试是否正确。
Linux下的编译工具——gcc • 语法:gcc [选项] 文件列表 • 用途:此命令用于调用C语言编译系统,运行时完成预处理、编译、汇编和连接4个步骤并最终生成可执行文件。 • 默认情况下产生的可执行程序被保存为a.out文件。 • 常用选项: • -c 跳过连接保留目标文件(.o) • -g 创建用于gdb的符号表和调试信息 • -l 链接库文件 • -o 指定可执行文件的文件名 • -O[n] 根据指定的级别对程序进行优化 • -Wall 产生尽量多的警告信息
Step1:编写hello主程序 • int main() • { • printf(“hello!\n”); • return 0; • } • gcc –Wall a.c
Step1:编写hello主程序 • #include “stdio.h” • int main() • { • printf(“hello!\n”); • return 0; • } • gcc –Wall a.c • ./a.out • gcc –Wall –o test a.c
Step1:编写hello主程序 • gcc –g –Wall –o test a.c • 比较一下有-g和没有-g生成的可执行文件的大小?
Step2:编写带参数输入的主程序 • #include “stdio.h” • #include “stdlib.h” • int main(intargc, char *argv[]) • { • if (argc < 3) • { • printf(“please input x, y!\n”); • } • else • { • int x = atoi(argv[1]); • int y = atoi(argv[2]); • printf(“arg1=%s, arg2=%s\n”, argv[1], argv[2]); • printf(“x=%d, y=%d\n”, x, y); • } • return 0; • }
Step3:编写f.c • #include “math.h” • double f(int x, int y) • { • double xx = (double)x; • double yy = (double)y; • double a = pow(xx, yy) + 2; • return a; • } • gcc –Wall –o test a.c f.c -lm
Step4:修改test.c调用f函数 • #include “stdio.h” • #include “stdlib.h” • extern double f(int x, int y); • int main(int argc, char *argv[]) • { • if (argc < 3) • { • printf(“please input x, y!\n”); • } • else • { • int x = atoi(argv[1]); • int y = atoi(argv[2]); • double a = f(x, y); • printf(“x=%d, y=%d, pow(x, y)+2=%f\n”, x, y, a); • } • return 0; • }
Step5:编写自己的makefile • 语法:目标文件列表:依赖文件列表 • <Tab>命令列表 • test : a.c f.c gcc –Wall –o test a.c f.c -lm • test : a.o f.o gcc –Wall –o test a.o f.o –lm • a.o : a.c gcc –c a.c • f.o : f.c gcc –c f.c
Step5:编写自己的makefile • CC=gcc • CFLAGS=-Wall • LIBS=-lm • OBJS=a.o f.o • TARGET=test • RM = rm -f • $(TARGET) : $(OBJS) $(CC) $(CFALGS) –o $(TARGET) $(OBJS) $(LIBS) • $(OBJS) : %.o : %.c $(CC) –c $(CFALGS) $< -o $@ • clean : -$(RM) $(TARGET) $(OBJS)
Step6:请输入测试数据进行测试 • x = 3, y = 4 • x = 10, y = 0 • x = 0, y = 2 • x = -2, y = 5 • x = -2, y = -5