如何告诉编译器不优化某些代码?

Fra*_*ank 3 c++ compiler-construction optimization templates function

有没有办法告诉编译器(在我的情况下是g ++)优化某些代码,即使该代码不可访问?我只想在目标文件中使用这些符号.

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

void foo(){
  Foo<int> v;
}
Run Code Online (Sandbox Code Playgroud)

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

extern bool bar;
void foo(){
  if(bar){
    Foo<int> v;
  }
}
Run Code Online (Sandbox Code Playgroud)

但那似乎并没有这样做.

(如果你真的想知道为什么我在地球上会想要那个 - 它与这个问题有关,而不是显式的模板实例化template class Foo<int>我只是想能够写Foo<int> v,因为在很多情况下这更容易,因为它隐含地实例化所需的所有函数,它在没有优化的情况下在调试模式下工作正常......)

更新:

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

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

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

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

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

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

main.cpp中

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

int main(int argc, char** argv){
  Foo<int> foo(1);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译(无优化)

g++ -c main.cpp
g++ -c foo-instantiation.cpp
g++ main.o foo-instantiation.oo
Run Code Online (Sandbox Code Playgroud)

编译(优化)

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
Run Code Online (Sandbox Code Playgroud)
  • 我尝试使用预编译头,但模板实例化方法可以更快地编译.
  • foo-instantiation.cpp没有优化的编译并不是那么理想,因为库代码(foo.h和其他代码)会运行得更慢.

小智 7

您正在遇到一个定义规则.在一个文件中,您有一个定义:

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

在另一个不同的定义:

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

这在C++中是明确不允许的(只允许一个相同的定义),如果你违反了规则,你的代码有时似乎可以工作,但你实际拥有的是可怕的"未定义的行为" - 根据阶段的不同,任何事情都可能发生月亮(但更可能是某些关键时刻编译器的内部状态).

基本上,你不能写那样的代码 - 抱歉.