使用gcc编写一个应用程序: 该程序包含三个.c 文件:main.c add.c swap.c

使用gcc编写一个应用程序: 该程序包含三个.c 文件:main.c add.c swap.c,第1张

int add(int 码迟盯x, int y)

{

  return x + y

} void swap(int *x, int *y)

{

  int 旦答t = *x *x = *y *y = t

} #include <stdio.h>

int add(int x, int y)

void swap(int *x, int *y)

int main()

{

  int a, b, c

  printf("Please input two integer: ")

  scanf("%d%d", &a, &b)

  c = add(a, b)

  printf("add(a, b) = %d\n", c)

  swap(&a, &b)

  printf("迟和a = %d, b = %d\n", a, b)

  return 0

}

方法/步骤

1、编写c代码,并输入以下代码,生成文件hello.c

[root@wahoo

test]#

vim

hello.c

#include

<stdio.h>

#define

DISPLAY

"hello

c!"

int

main(void)

{

printf("%s\n",

DISPLAY

)

return

0

}

ZZ(说明:ZZ当前文件进行快速保存 *** 作

2、预编译(Preprocessing)

会对各种预处理指令(#include

#define

#ifdef

等#开始的代码行)进行处理,删除注释和多余的空白字符,生成一份新的代码

[root@wahoo

test]#gcc

-E

hello.c

-o

hello.i

E

参数

通知gcc对目标文件进行预编译,这里是对文件hello.c文件

o

参数

是对命令输出结果进行导入 *** 作,这里是把

gcc

-E

hello.c

*** 作结果输出到文件hello.i(命名要自定义)中进行保存

这个命令执行完后我们目录下多了一个文件hello.i,你可以查阅一下文件的内容。

3、编译(Compilation)

对代码进行语法、语义分析和错误判断,生成汇编代码文件

[root@wahoo

test]#gcc

-S

hello.i

-o

hello.s

S

参数

通知gcc对目标文件进行编燃竖译,这里是对文件hello.i文件

通过这一步我们知道

C语言跟汇编的

关系,至于他们之前是如何进行转换的,大家可以进行更深入的学习与探讨。

此时纤段和目录下多了一个hello.s文件,内容如图

4、汇编(Assembly)

把汇编代码转换与计算机可认识的二进毁盯制文件,要知道计算机只认识0和1呢

[root@wahoo

test]#gcc

-c

hello.s

-o

hello.o

c

参数

通知gcc对目标文件执行指令转换 *** 作

此步骤我们得到文件hello.o

大家也同样打开文件查看一下,这个文件里面几乎没几个字符大家能看懂,这就对了,但大家可以通过这种方法将其转化为我们可读的形式:

[root@wahoo

test]#readelf

-a

hello.o

5、链接(Linking/Build)

通俗的讲就是把多个*.o文件合并成一个可执行文件,二进制指令文件

[root@wahoo

test]#gcc

hello.o

-o

hello

这里我们就得到了一个可以直接在系统下执行的文件

hello

我们也可以对这个文件进行readelf *** 作,也可以进行二进制指令转汇编的 *** 作

[root@wahoo

test]#objdump

-d

hello

6、程序运行

[root@wahoo

test]#./hello

hello

c!

7、总结:gcc

编译c程序的主要过程包括

预编译->编译->汇编->连接

四个过程,每个过程都分别进行不同的处理,了解了这其中的一些原理,对c编程的理解大有益处

#include <iostream>

using namespace std

int main(void) {

int i, sum = 0

for (i = 1 i <= 100 i++)

sum += i

cout <<稿茄 sum << 芹弯endl

return 0

}

code本身完全没有问题。我认为是键首察你GCC没有安装或配置好。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12308593.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存