文章目录
安装:
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:头文件中直接包含函数定义。
- 创建hello.h
gedit hello.h
void hello()
{
cout<<"hello.h"<<endl;
}
- 创建main.cpp
gedit main.cpp
#include<iostream>
using namespace std;
#include"hello.h"
int main()
{
hello();
cout<<"main.cpp"<<endl;
return 0;
}
- 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