Ubuntu的gcc、g++入门


安装:

sudo apt-get update
sudo apt-get g++
sudo apt-get gcc
sudo apt-get install cmake
sudo apt-get install build-essential

一、gcc/g++的安装和简单使用

1.查看版本是否一致

gcc --version
g++ --version

一般来说是一致的:
在这里插入图片描述
如果不一致,要安装成一致的:
https://blog.csdn.net/csdn_zhishui/article/details/83751120

2.gcc编译第一个c语言程序

(1)编写程序

就在当前目录下写一个文件吧

gedit main.c
#include<stdio.h>
int main()
{
	printf("hello\n");
	return 0;
}

(2)编译执行程序

写法1:默认生成文件a.out

gcc <文件名(包括.后缀)>
./a.out

在这里插入图片描述

写法2:自定义生成文件名

gcc <文件名(包括.后缀)> -o <生成文件名>
./<生成文件名>

生成文件名的.out后缀要么都有,要么都没有,保持一致。
在这里插入图片描述

3.g++编译第一个c++语言程序

(1)编写程序

编写程序

gedit main.cpp
#include<iostream>
using namespace std;
int main()
{
	cout<<"hello\n";
	return 0;
}

(2)编译程序

写法1:默认生成文件a.out

g++ <文件名(包括.后缀)>
./a.out

在这里插入图片描述

写法2:自定义生成文件名

g++ <文件名(包括.后缀)> -o <生成文件名>
./<生成文件名>

生成文件名的.out后缀要么都有,要么都没有,保持一致。

在这里插入图片描述

二、编译一个包含简单头文件的程序

1.实现

c和c++一样,这里拿c++举例。

程序共两个文件:

  • main.cpp:main()函数入口
  • hello.h:头文件中直接包含函数定义。
  1. 创建hello.h
gedit hello.h
void hello()
{
	cout<<"hello.h"<<endl;
}
  1. 创建main.cpp
gedit main.cpp
#include<iostream>
using namespace std;
#include"hello.h"
int main()
{
	hello();
	cout<<"main.cpp"<<endl;
	return 0;
}
  1. g++编译执行
g++ main.cpp
./a.out

2.易错点

(1)头文件的理解

注意main.cpp#include<hello.h>是声明在using namespace std之后的,如果声明在之前,那么就会报错:cout和endl未声明。

这是因为头文件其实是替换

#include<iostream>
using namespace std;
void hello()
{
	cout<<"hello.h"<<endl;
}
int main()
{
	hello();
	cout<<"main.cpp"<<endl;
	return 0;
}

这样自然就解释了为什么会有顺序。

(2)g++的执行

g++执行的时候只用执行main.cpp就行,打上hello.h反而出错

g++ main.cpp hello.h

报错:

hello.h: In function ‘void hello()’:
hello.h:3:2: error: ‘cout’ was not declared in this scope
  cout<<"hello.h"<<endl;
  ^
hello.h:3:19: error: ‘endl’ was not declared in this scope
  cout<<"hello.h"<<endl;

三、使用c++11

格式

g++ main.cpp -o main -std=c++11
./main

例子:如使用#include<pthread>会出问题

#include<iostream>
#include<thread>
using namespace std;

void hello()
{
    cout<<"hello"<<endl;
}
 
int main()
{
    thread thread1(hello);
    thread1.join();
    cout<<"completion"<<endl;
    return 0;
}
g++ main.cpp -o main -std=c++11 -pthread
./main

PS:-lpthread和-pthread的区别

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值