我是靠谱客的博主 聪明菠萝,这篇文章主要介绍c++ g++ 如何编译class文件,现在分享给大家,希望可以做个参考。

将类,通过分离出主程序后, 如何用g++编译呢?

比如
Person.h

Person.cpp

main.cpp
其中:main是主程序,但是类在Person.h Person.cpp中得以实现;

复制代码
1
2
g++ Person.cpp main.cpp - o main

此时不必编译Person.h文件,因为在Person.cpp中一定写了:

复制代码
1
2
#include "Perosn.h"

这样的话g++会自动寻找当前文件夹下的头文件

例子:
person.h文件:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma once #include <iostream> using namespace std; template <class T> class Person { private: /* data */ T mage; public: Person(T age); ~Person(); };

person.hpp文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "person.h" template <class T> Person<T>::Person(T age):mage(age) { cout << "ok " <<endl; cout << this->mage<<endl; } template <class T> Person<T>::~Person() { }

mian 文件
为什么变成了hpp文件?
hpp文件是一种类的模版文件,本质是cpp文件,在g++编译器中,不需要编译它。

复制代码
1
2
3
4
5
6
7
8
#include <iostream> #include "person.hpp" using namespace std; int main(){ Person<int> s(2); return 0; }

g++编译指令:

复制代码
1
2
g++ main.cpp -o ./output/run

最后

以上就是聪明菠萝最近收集整理的关于c++ g++ 如何编译class文件的全部内容,更多相关c++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部