无法更改为C++ 11

问题描述:

为什么我不能编译我的代码,以C++ 11并使用srand48功能后使用srand48()?无法更改为C++ 11

我有一个程序,我玩的一些矩阵。 问题是,当我用-std=c++0x标志编译代码时。 我想使用一些C++ 11的唯一功能,这是我的做法。 编译没有任何问题,如果我没有指定C++版本。像这样:

g++ -O2 -Wall test.cpp -o test -g 

如果我误解了所提到的标志,请纠正我。

我在Windows 7 64位机器上运行我的代码并通过cygwin编译。我使用g ++版本4.5.3(GCC)。如果需要更多信息,请发表评论。

对于一些未知的原因(甚至自己),那么我所有的代码写在一个编译单元。 如果错误是由结构性错误引起的,那么您也应该随时指出。 :)

,收到以下错误

g++ -std=c++0x -O2 -Wall test.cpp -o test -g 

test.cpp: In function ‘void gen_mat(T*, size_t)’: 
test.cpp:28:16: error: there are no arguments to ‘srand48’ that depend on a template parameter, so a declaration of ‘srand48’ must be available 
test.cpp:28:16: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated) 
test.cpp:33:28: error: there are no arguments to ‘drand48’ that depend on a template parameter, so a declaration of ‘drand48’ must be available 

这里是我的代码子,它产生以上所示的错误。

#include <iostream> 
#include <cstdlib> 
#include <cassert> 
#include <cstring> 
#include <limits.h> 
#include <math.h> 

#define RANGE(S) (S) 

// Precision for checking identity. 
#define PRECISION 1e-10 

using namespace std; 

template <typename T> 
void gen_mat(T *a, size_t dim) 
{ 
    srand48(dim); 
    for(size_t i = 0; i < dim; ++i) 
    { 
     for(size_t j = 0; j < dim; ++j) 
     { 
      T z = (drand48() - 0.5)*RANGE(dim); 
      a[i*dim+j] = (z < 10*PRECISION && z > -10*PRECISION) ? 0.0 : z; 
     } 
    } 
} 

int main(int argc, char *argv[]) 
{ 

} 

问候金。

这是解决方案是解决了这个问题对我来说:

首先N.M.解释说在使用-std=c++0x编译时不能使用srand()。 正确的标志使用是-std=gnu++11但是它需要G ++版本4.7+ 因此,对我来说,解决办法是编译我的代码-std=gnu++0x 编译命令= g++ -O2 -Wall test.cpp -o test -g -std=gnu++0x

+0

而在你真实的代码中你包含''? –

+0

是的,我会将我的包含添加到帖子中。 –

+0

还要记住,在包含''之前(参见http://linux.die.net/man/3/drand48),您可能必须''定义'_SVID_SOURCE'或'_XOPEN_SOURCE'。 –

如果您明确设置-stc=c++03你会得到同样的错误。这是因为drand48和朋友实际上并不是任何C++标准的一部分。 gcc将这些功能作为扩展名包含在内,并在请求标准行为时禁用它们。

g++默认的标准模式实际上是-std=gnu++03。您可能需要使用-std=gnu++11而不是-std=c++0x,或者将-U__STRICT_ANSI__传递给编译器。

+0

*“您可能想要使用'-std = gnu ++ 11'”* - 相反'gnu ++ 0x',因为'gnu ++ 11'(如'C++ 11')仅适用于* gcc 4.7 + *。或者首先使用* C++ 11 *的平台无关的随机数设施。 –

+0

@ChristianRau它适用于-std = gnu ++ 0x。非常感谢你。如果你作出答案,我会接受它作为解决方案,否则我会将nms答案标记为正确:) –

+0

@ KimA.Jakobsen这真的是* nm *的答案,只是'gnu ++ 0x'而不是'gnu + + 11',这使得对我来说单独的回答会非常荒谬。可能的答案是使用* C++ 11 *的随机数生成器而不是* C *(这比平台相关的GNU更适合),但我不确定那会真的回答你的实际问题要么是(无论如何,我不明白你的代码是否足够)。 –