示例:这里有一个简单的函数,即使从未调用,我也希望该函数被编译。
void foo(){
Foo<int> v;
}
如果没有官方的编译器指令,有没有什么技巧可以让编译器认为这是一个重要的函数?或者至少让它认为它不能被安全地忽略?我尝试了类似于这样的方法:
extern bool bar;
void foo(){
if(bar){
Foo<int> v;
}
}
但似乎这样做不行。
(如果你真的想知道我为什么要这样做——与这个问题有关,其中,我不想使用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
}
};
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中提取的接口文件。
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
- 我尝试使用预编译头文件,但是使用模板实例化方法可以使编译速度更快。
- 不使用优化编译
foo-instantiation.cpp
并不理想,因为这会导致库代码(foo.h
和其他)运行速度变慢。