您的位置:首页 > 编程语言 > C语言/C++

分别使用mingw和visual studio对cpp文件编译

2016-01-18 23:39 495 查看

c++编译

标签(空格分隔): 未分类

总结一下如何使用visual studio 和mingw编译c++文件

单文件编译:

/* a.cpp */
#include <iostream>
int main(){
std::cout<<"hello pepelu"<<std::endl;
return 0;
}

使用mingw编译:

一步到位:

g++ a.cpp

生成名为a的可执行文件。

指定生成文件名的编译方式:

g++ a.cpp -o fileName

生成名为fileName的可执行文件

使用visual studio编译:

cl /EHsc a.cpp

生成a.exe,a.obj其中a.exe为可执行文件

包含头文件

/* a.cpp */
#include <iostream>
#include "a.h"

void a::foo()
{
std::cout<<"hello pepelu"<<std::endl;
}

int main()
{
a _a;
_a.foo();
return 0;
}

头文件:

/* a.h */
#ifndef A_H
#define A_H
class a
{
public:
a(){}
~a(){}
void foo();
};
#endif

使用mingw编译:

g++ a.cpp

或者:

g++ a.cpp -o fileName

使用visual studio编译:

cl /EHsc a.cpp

自动链接头文件

也可以为头文件指定文件目录:

cl /EHsc /I${filePath} a.cpp

filePath为头文件所在目录。

多文件编译:

/* c.h */
#ifndef C_H
#define C_H
#include <iostream>
#include <string>

using namespace std;

extern string s1;
extern string s2;

extern void fun1();
extern void  fun2();
#endif

/* b.cpp */
#include "c.h"

string s1="";
string s2="";

void fun1()
{
s1="Now in fun1...";
cout<<s1<<endl;
}

void fun2()
{
s2="Now in fun2...";
cout<<s2<<endl;
}

/* a.cpp */
//main
#include "c.h"

int main()
{
cout<<"s1 = "<<s1<<endl;
cout<<"s2 = "<<s2<<endl;
fun1();
fun2();
cout<<"s1 = "<<s1<<endl;
cout<<"s2 = "<<s2<<endl;
return 0;
}

使用mingw编译:

g++ a.cpp b.cpp -o fileName

一步即可生成以fileName为文件名的可执行文件。

分布编译:

g++ -c a.cpp
g++ -c b.cpp
g++ a.o b.o -o fileName

依次执行即可得到以fileName命名的可执行文件。

使用visual studio编译

cl /EHsc a.cpp b.cpp

自动链接。

参考:

http://wiki.ubuntu.org.cn/index.php?title=Compiling_Cpp&variant=zh-hans

https://msdn.microsoft.com/zh-cn/library/6t3612sk.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: