代码之家  ›  专栏  ›  技术社区  ›  Darius Duesentrieb

启用优化的g++和clang++的奇怪行为[duplicate]

  •  -1
  • Darius Duesentrieb  · 技术社区  · 7 年前

    以下是我的程序:

    #pragma once
    
    #include <iostream>
    
    template<size_t p>
    void print()
    {
      std::cout << "" << __FILE__ << "" <<  __LINE__ << "" << std::endl;
      exit(0);
    }
    

    打印.cpp:

    #include "print.hpp"
    
    template<>
    void print<13>()
    {
      std::cout << "Unlucky." << std::endl;
    }
    

    主.cpp:

    #include <iostream>
    #include "print.hpp"
    
    int main()
    {
      std::cout << "Started." << std::endl;
      print<13>();
      std::cout << "Exiting." << std::endl;
    }
    

    当我用 g++ main.cpp print.cpp -O0 -std=c++11 && ./a.out 工作正常(输出为:

    Started.
    Unlucky.
    Exiting.
    

    但是,如果我用 g++ main.cpp print.cpp -O1 -std=c++11 && ./a.out

    Started.
    Unlucky.
    Speicherzugriffsfehler //German for memory access error
    

    与clang++几乎一样,如果不进行优化,它也能很好地完成工作 当-O1或更高时,它输出:

    Started.
    Unlucky.
    ./print.hpp8
    

    为什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   R Sahu    7 年前

    您需要在.hpp文件中声明模板专用化。

    template<size_t p>
    void print()
    {
      std::cout << "" << __FILE__ << "" <<  __LINE__ << "" << std::endl;
      exit(0);
    }
    
    // Declare the specialization.
    template<> void print<13>();
    

    如果没有.hpp文件中的声明,我会在g++6.4.0中遇到一个链接器错误。

    .../Local/Temp/cctCC5MK.o:print.cc:(.text+0x0): multiple definition of `void print<13ul>()'
    .../Local/Temp/ccgodRUG.o:socc.cc:(.text$_Z5printILm13EEvv[_Z5printILm13EEvv]+0x0): first defined here
    collect2: error: ld returned 1 exit status