有没有办法告诉编译器(在我的例子中是 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/