为什么C ++ std :: min在O0上编译时不能使用静态字段作为其参数? [英] why does c++ std::min can't use a static field as its parameter when compile on O0?
问题描述
相同的代码,用O0编译,它将报告错误:
same code, compile with O0, it will report an error:
//============================================================================
// Name : test.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdint.h>
using namespace std;
class foo{
static const int64_t MAX_THREAD_NUM = 10 * 1000;
public:
void test();
};
void foo::test(){
int64_t a = 100;
// int64_t tmp = MAX_THREAD_NUM;
// int64_t min = std::min(tmp, a);
int64_t min = std::min(MAX_THREAD_NUM, a);
cout << min << endl; // prints !!!Hello World!!!
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.o" -o "src/test.o" "../src/test.cpp"
g++ -o "test" ./src/test.o
./src/test.o: In function `foo::test()':
/home/foo/eclipse-workspace/test/Debug/../src/test.cpp:27: undefined reference to `foo::MAX_THREAD_NUM'
collect2: error: ld returned 1 exit status
/home/foo/eclipse-workspace/test/Debug/../src/test.cpp:27: undefined reference to `foo::MAX_THREAD_NUM'
但是带有O2标志,它可以编译成功.
but with O2 flag, it can compile succeed.
g++ -O2 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.o" -o "src/test.o" "../src/test.cpp"
g++ -o "test" ./src/test.o
g ++版本:g ++(Ubuntu 4.8.5-4ubuntu8)4.8.5版权所有(C)2015自由软件基金会,Inc.这是免费软件;请参阅复制条件的来源.没有保修单;甚至不是针对特定目的的适销性或适用性
g++ version: g++ (Ubuntu 4.8.5-4ubuntu8) 4.8.5 Copyright (C) 2015 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
推荐答案
程序不正确,不需要通过提供ODR使用的符号(std :: min
通过引用接受其参数).
Program is ill-formed no diagnostic required (NDR) as you break One Definition Rule (ODR) by not providing definition of ODR-used symbol (std::min
takes its argument by reference).
优化器会删除未使用的代码,并让您认为它是正确的.
The optimizer removes that unused code and lets you think it is correct.
这篇关于为什么C ++ std :: min在O0上编译时不能使用静态字段作为其参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!