September 19, 2005

Awesome C++

剛剛閱讀 Ranjit Mathew 的 blog [C++ Madness],讓我終於一「虧」C++ 之美。讓我們看看這個小程式:
    #include <string>
    #include <map>
    
    using namespace std;
    
    int main(void)
    {
      map<string,string> foo;
      return 0;
    }
    
嗯,看似相當簡單,當我們用 "g++ -fno-implicit-templates foo.cpp" 編譯的時候,竟然會印出難以置信的錯誤,請參閱以下圖片: (別懷疑,密麻麻的文字就是錯誤訊息,按一下可以看全圖)
這是怎麼了呢?錯誤訊息的長度遠遠多出我們的 C++ source code,引述 Ranjit Mathew 的說明:
    The example might look bogus, but consider this: you have been told that explicit template instantiations can some times considerably speed up your build process, not to mention save space used up by the object files, so you begin by creating an explicit instantiation file that you try to populate with template instantiations that are actually used by your program. You compile all other source files using "-fno-implicit-templates", but not the one special file. If you have not caught all template instantiations however, you will hit the monster of an error message that I sought to show per missing template instantiation. You are supposed to then figure out from these error messages which of the template instantiations you have missed out. Should anyone be surprised if you lose all hope at this point and just ditch the idea?
從 CCC User Manual 節錄出 "-fno-implicit-templates" 的語意:
    -fno-implicit-templates
      Never emit code for non-inline templates which are instantiated implicitly (i.e. by use); only emit code for explicit instantiations.
嗯,好個 C++ Madness, awesome !
由 jserv 發表於 September 19, 2005 03:54 PM
迴響

在 g++ 3.2 裡面,錯誤訊息短了一點,而且較有脈絡:

Undefined first referenced symbol in file
[略]
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status


再回顧一下 -fno-implicit-templates 編譯設定,大概就可揣摩出是怎麼一回事。

不過,C++ template 不易除錯,算是致命的老問題了。所以除非很有把握,否則應盡量不要自作聰明去改變 template 的編譯設定。 :)

william 發表於 September 20, 2005 12:10 PM
發表迴響









記住我的資訊?