Ubuntu系统下配置C语言编译环境

嵌入式技术

1330人已加入

描述

配置gcc

对于一个全新的Ubuntu系统,可能还没有配置C语言编译环境,这时候需要用户自己安装。

:~$ gcc -v
Command 'gcc' not found, but can be installed with:
sudo apt install gcc

查看版本gcc -v,确实没有C语言编译环境gcc

:~$ apt-get install gcc 
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
:~$ sudo apt-get install gcc 
[sudo] password for alice: 
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done

用apt命令配置gcc环境apt-get install gcc ,首次尝试未能成功,因为没有管理员权限,加上sudo, sudo apt-get****install gcc 再次尝试,可以看到成功安装。

:~$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu

至此,gcc环境配置成功。编写一个C语言程序测试

#include < stdio.h >


int main(){
    printf("hello world!n");
    return 0;
}

测试文件test.c放在Document下面,经过编译gcc test.c 、运行./a. out ,成功输出“hello world!”

:~/Documents$ vi test.c
:~/Documents$ gcc test.c 
:~/Documents$ ls
a.out  test.c
:~/Documents$ ./a.out 
hello world!

配置Makefile

Makefile可以很好地管理C语言程序,Makefile的配置与gcc类似。

:~$ make -v
Command 'make' not found, but can be installed with:
sudo apt install make        # version 4.3-4.1build1, or
sudo apt install make-guile  # version 4.3-4.1build1

查看系统make -v,确实没有make环境,现在配置该环境sudo apt-get install make

:~$ sudo apt-get install make
[sudo] password for alice: 
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Suggested packages:
  make-doc
The following NEW packages will be installed:
  make

再次查看,make环境配置完成

:~$ make -v
GNU Make 4.3
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2020 Free Software Foundation, Inc.

利用上述C语言程序,测试makefile,在Makefile文件中,写入下面的代码(其中Makefile首字母大写,没有后缀名)

test : test.o
  gcc -o test test.o


test.o : test.c
  gcc -c -o test.o test.c


clean :
  rm -f main test.o

每一行命令的gcc前面,一定是Tab键,不是空格,否则编译make报错。

:~/Documents$ make
gcc -c -o test.o test.c
gcc -o test test.o
:~/Documents$ ./test 
hello world!
:~/Documents$ ls
a.out  Makefile  test  test.c  test.o

经过编译make、运行./test ,仍然可以正确输出。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分