c++ - 如何告诉编译器不要优化某些代码?

标签 c++ optimization templates compiler-construction function

有没有办法告诉编译器(在我的例子中是 g++)优化某些代码,即使该代码不可访问?我只想要目标文件中的那些符号。

示例:这是一个简单的函数,我确实希望编译该函数,即使它从未被调用。

void foo(){
  Foo<int> v;
}

如果没有官方的编译器指令,是否有技巧让编译器认为它是一个重要的功能?或者至少让它认为不能安全地忽略它?我试过这样的事情:

extern bool bar;
void foo(){
  if(bar){
    Foo<int> v;
  }
}

但这似乎并没有做到。

(如果你真的想知道为什么我到底想要那个——它与 this 问题有关,在这里,我只是想能够写 template class Foo<int> 而不是使用 Foo<int> v 的显式模板实例化,因为在许多情况下这更容易,因为它隐式实例化了所有需要的函数,并且在没有优化的 Debug模式下也能正常工作……)

更新:

这是我想要做的(作为一个可编译的迷你示例):

foo.h(这些文件是给我的,不可更改)

template<class T>
struct Foo {
  T val_;
  Foo(T val) : val_(val) {
      // heavy code, long compile times
  }
};

foo-instantiation.cpp

#include "foo.h"
void neverCalled() {
  Foo<int> f(1);
}

// The standard way to instantiate it is this:
// template class Foo<int>;
// but in reality it is often hard to find out 
// exactly what types I have to declare.
// Usage like Foo<int> f(1); will instantiate all
// dependent types if necessary.

foo-decl.h(我从 foo.h 中提取的接口(interface))

template<class T>
struct Foo {
  T val_;
  Foo(T val); // no heavy code, can include anywhere and compile fast
};

main.cpp

#include <iostream>
#include "foo-decl.h"

int main(int argc, char** argv){
  Foo<int> foo(1);
  return 0;
}

编译(无优化)

g++ -c main.cpp
g++ -c foo-instantiation.cpp
g++ main.o foo-instantiation.oo

编译(优化)

g++ -O2 -c main.cpp
g++ -O2 -c foo-instantiation.cpp
g++ main.o foo-instantiation.oo
main.o(.text+0x13): In function `main':
: undefined reference to `Foo<int>::Foo(int)'
collect2: ld returned 1 exit status
  • 我尝试使用预编译 header ,但模板实例化方法可以加快编译速度。
  • 在没有优化的情况下编译 foo-instantiation.cpp 并不是那么理想,因为这样库代码(foo.h 和其他)将运行得更慢。

最佳答案

您遇到了单一定义规则。在一个文件中你有一个定义:

template<class T>
struct Foo {
  T val_;
  Foo(T val) : val_(val) {
      // heavy code, long compile times
  }
};

还有一个不同的定义:

template<class T>
struct Foo {
  T val_;
  Foo(T val); // no heavy code, can include anywhere and compile fast
};

这在 C++ 中是明确不允许的(只允许一个相同的定义),如果你违反规则,你的代码有时看起来很正常,但你实际上拥有的是可怕的“未定义行为”——任何事情都可能发生,具体取决于月相(但更可能是编译器在某些关键时刻的内部状态)。

基本上,您不能编写那样的代码 - 抱歉。

关于c++ - 如何告诉编译器不要优化某些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/668103/

相关文章:

c++ - 如何向 vector<>::pointer 添加 const 限定符?

c++ - 如何检查 C++ API 的性能

html - 使用wordpress加载文档的长时间延迟

c++ - 由于优化代码重新排序

c++ - C++中如何判断一个字符是否合法

html - 强制图像不换行

c++ - std::function 可以是类数据成员吗?

c++ - Facebook warpdrive 构建 - D 编程语言

c++ - 使用/O2 与/Ox 编译——哪个更快(根据经验)?

templates - 无逻辑模板(例如 mustache )有什么优点?