GCC直接编译代码

参考文章:

http://www.linuxidc.com/Linux/2011-01/31227.htm


1.单个文件编译

编写源文件hello.c

编译:gcc hello.c

生成a.out


指定生成文件名:gcc -o test  hello.c

生成test


2.编译成目标文件

编译:gcc  -c  hello.c

生成:hello.o

指定生成文件名:gcc -c  -o test.o hello.c

编译:gcc -c file1.c file2.c file3.c

生成:file1.o file2.o  file3.o


3.多文件编译

编写计算字符串长度函数string.c如下:

#define ENDSTRING '\0'
int StrLen(char *string)
{
 int len=0;
 while(*string++ != ENDSTRING)
 len++;
 return len;
}

编写主函数main.c 如下:

#include<stdio.h>

extern int StrLen(char* str);

int mian(void)

{

char src[]="Hello Dymatic";
printf("string length is: %d\n",StrLen(src));
return 0;
}

编译:gcc -o test  string.c main.c

生成:test

执行结果:string length is: 13

也可先生成目标文件:gcc -c string.c main.c

编译:gcc -o test string.o main.o


### 代码概述 你希望使用 `gcc` 编译一段 C 代码。结合你之前提供的代码片段,该代码存在语法错误、标点错误和逻辑缺陷,**无法直接编译通过**。 --- ### 代码解析 原始代码(含错误): ```c #include<stdio.h> int copy_array(int*array,int count){ int i; int*myarray=(int*))malloc(count*sizeof(int)); if(myarray==NULL) return -1; for(i = 0;i < count;i++); myarray[]=array[]; return count; } ``` #### 编译命令尝试: ```bash gcc -o copy copy.c ``` 将报出以下典型错误: | 错误类型 | 示例 | |--------|------| | 中文标点 | `error: expected ‘;’ before ‘{’ token` | | 多余括号 | `error: expected expression before ‘)’ token` | | 数组语法错误 | `error: expected identifier or ‘(’ before ‘[’ token` | | 未声明的函数 | `warning: implicit declaration of function ‘malloc’` | --- ### ✅ 正确编译流程 #### 第一步:修复代码(完整可编译版本) ```c #include <stdio.h> #include <stdlib.h> int* copy_array(int* array, int count) { int i; int* myarray = (int*)malloc(count * sizeof(int)); if (myarray == NULL) return NULL; for (i = 0; i < count; i++) { myarray[i] = array[i]; } return myarray; } // 主函数示例 int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; int* copied = copy_array(arr, n); if (copied != NULL) { for (int i = 0; i < n; i++) { printf("%d ", copied[i]); } printf("\n"); free(copied); // 释放内存 } else { printf("Memory allocation failed.\n"); } return 0; } ``` #### 第二步:保存为 `.c` 文件 ```bash nano copy.c # 粘贴修复后的代码,保存退出 ``` #### 第三步:使用 `gcc` 编译 ```bash gcc -o copy copy.c ``` #### 第四步:运行程序 ```bash ./copy ``` 输出: ``` 1 2 3 4 5 ``` #### 推荐编译选项(增强安全性与警告检查): ```bash gcc -Wall -Wextra -std=c99 -pedantic -O2 -o copy copy.c ``` --- ### 知识点 1. **`gcc` 编译基本语法** `gcc [源文件] -o [可执行文件]`,自动完成预处理、编译、汇编、链接。 2. **`-Wall` 启用警告** 显示常见编程错误,帮助发现潜在问题,提高代码质量。 3. **动态内存管理** 使用 `malloc` 后必须 `free`,避免内存泄漏,且需包含 `<stdlib.h>`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值