更改为c ++ 11后无法使用srand48()

Kim*_*sen 5 cygwin g++ srand c++11

为什么我无法将代码编译为c ++ 11并使用srand48函数?

我有一个程序,我可以在其中使用一些矩阵.问题是当我用-std=c++0x标志编译代码时.我想使用一些仅限c ++ 11的函数,这是我的方法.如果我没有指定c ++版本,它编译没有任何问题.像这样:

g++ -O2 -Wall test.cpp -o test -g
Run Code Online (Sandbox Code Playgroud)

如果我误解了上述标志的作用,请纠正我.

我在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
Run Code Online (Sandbox Code Playgroud)

这是我的代码的子代码,它会生成上面显示的错误.

#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[])
{

}
Run Code Online (Sandbox Code Playgroud)

关心金.

这是解决我这个问题的解决方案:

第一个nm解释了编译时不能使用srand()-std=c++0x.使用正确的标志是-std=gnu++11需要g ++版本4.7+因此,我的解决方案是使用-std=gnu++0x 编译命令编译我的代码=g++ -O2 -Wall test.cpp -o test -g -std=gnu++0x

n. *_* m. 6

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

g++实际上是默认的标准模式-std=gnu++03.您可能希望使用-std=gnu++11而不是-std=c++0x传递 -U__STRICT_ANSI__给编译器.