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

Odd behaviour of g++ and clang++ with enabled optimization

本文关键字:优化 g++ 启用 clang++      更新时间:2023-10-16

这是我的程序:

打印.hpp:

#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

为什么?

您需要在 .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

我不确定如何在没有声明的情况下成功构建程序。