用c++标准库在linux上编译

Compiling on linux with c++ standard libraries

本文关键字:linux 编译 c++ 标准      更新时间:2023-10-16

我有以下示例代码:

function .h -函数头文件

#include <vector>
#include <tuple>
using std::vector;
using std::tuple;
tuple <double,double> A(vector<int>& n);

function .cpp - function cpp文件

#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
tuple <double,double> A(vector<int>& n)
{
  double a1=n.size();
  double a2=a1+0.5;
  return make_tuple(a1,a2);
}

main.cpp -主cpp文件

#include <iostream>
#include <vector>
#include <tuple>
#include "func.h"
using namespace std;
int main()
{
   double a1,a2;
   vector<int> n;
   n.push_back(1);
   n.push_back(2);
   tie(a1,a2)=A(n);
   return 0;
}

在visual studio中可以很好地编译。

我在Linux (gcc版本4.4.7 20120313 Red Hat 4.4.7-11)上编译它有问题:

g++ -03 -std=c++0x main.cpp func.cpp -lm

不编译,我得到以下错误:

1. In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/array:35,from main.cpp:5:/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/c++0x_warning.h:31:2: error: #error This file requires compiler and library suppcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
2. ‘std::tuple’ has not been declared
3. expected constructor, destructor, or type conversion before ‘<’ token

任何关于如何处理这个问题的指导都会很有帮助!

您告诉GCC输出到名为"-std=c++0x"的文件,因此根本没有设置该选项,导致此错误。我不知道后面的b会怎么样。但是你应该总是使用"-o outputfilename",而不是在"-o"选项和它的参数之间放置其他选项。

令人惊讶的是,错误似乎告诉您std=c++0x未设置。再次检查编译命令。应该是

g++ -std=c++0x -o b main.cpp func.cpp -O3 -lm

而非

g++ -o -std=c++0x b main.cpp func.cpp -03 -lm

我剪切并粘贴了您的三个文件(func.h, func.cppmain.cpp),我可以向您保证,在我的Linux盒子(CentOS 7.2)与g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)一切工作正常(您的原始命令有一些错误):

g++ -o myProg -O3 -std=c++0x main.cpp func.cpp -lm

更新你的GCC(甚至从源代码,如果你有几个小时;))。

如果您想在使用旧版本的Linux和GCC的服务器上运行可执行文件(从最新的c++ 11或c++ 14源代码编译),您的GCC 4.4不支持最新的c++标准,因为它出现在2009年,比c++ 11的发布日期(2011年)早,您可以尝试以下操作:

  • 在您自己的笔记本电脑(或计算机)上安装最新的Linux发行版,并通过运行g++ --version检查其GCC编译器至少是GCC 5(最好是GCC 6)(您可能需要使用g++-5而不是g++,等等…)

  • 使用g++ -static -std=c++14 -Wall func.cpp main.cpp -lm -o mybinprog静态编译和链接你的程序在那台笔记本电脑上(如果你想优化-O3和/或-g调试-最好在本地调试-)

  • 复制(例如使用scp mybinprog remotehost:)可执行文件到远程服务器并在那里运行

在较新的Linux(笔记本电脑)上构建的静态链接可执行文件很可能(但不确定)在某些较旧的Linux服务器上运行。

顺便说一句,要编译一个多源文件程序,最好学会如何使用GNU make

请注意,g++的程序参数顺序非常重要,因此请阅读有关调用GCC的文档。

<一口> p。从技术上讲,你甚至可以尝试动态链接C库和静态链接c++标准库。