简体   繁体   English

g++ 编译器不会为未定义的方法生成错误/警告

[英]g++ compiler not generating error/warning for undefined methods

I have a class that has a declared method but not defined/used anywhere.我有一个具有声明方法但未在任何地方定义/使用的类。 I expected this piece of code to generate linking error but it did not.我预计这段代码会产生链接错误,但它没有。 Looks like compiler is smart enough to remove dead code.看起来编译器足够聪明,可以删除死代码。 Which default optimization is doing this?哪个默认优化正在这样做? How can I explicitly disable it to generate the error?如何显式禁用它以生成错误?


#include <iostream>

using namespace std;

class Base{
public:
 int x;
 string name;
 void set(int val){ x = val;};
 int get(){ return x;}

 void Init();
};

int main() {
  Base base;
  base.set(10);
  cout << base.get() << endl;

  return 0;
}

EDIT1 : Here Init() function is not defined and neither used anywhere. EDIT1 :这里 Init() 函数没有定义,也没有在任何地方使用。 So, I expected compiler to complain about this not defined.所以,我希望编译器会抱怨这个没有定义。 But don't see any error/warning.但是没有看到任何错误/警告。

Thanks in advance.提前致谢。

Generally the linker will only produce errors for undefined symbols that are used.通常,链接器只会对使用的未定义符号产生错误。 As you never call Init there is no error.由于您从不调用Init ,因此没有错误。

Looks like compiler is smart enough to remove dead code.看起来编译器足够聪明,可以删除死代码。

The compiler is not even "smart" here.编译器在这里甚至不是“智能”。 There is no code using a function so that function is not needed to produce an executable program.没有代码使用函数,因此不需要函数来生成可执行程序。

The function is not even "ODR used" so technically the compiler would be wrong to require a definition.该函数甚至不是“使用 ODR”,因此从技术上讲,编译器要求定义是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM