启用优化的 g++ 和 clang++ 的奇怪行为
Odd behaviour of g++ and clang++ with enabled optimization
这是我的程序:
打印.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
我不确定如何在没有声明的情况下成功构建程序。
相关文章:
- 空基优化子对象的地址
- 关闭||运算符优化
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 返回值优化:显式移动还是隐式
- 人脸跟踪arduino代码的优化
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 纯函数,为什么没有优化
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 如何以优化的方式同时迭代两个间距不相等的数组
- 小字符串优化(调试与发布模式)
- 浮点定向舍入和优化
- Visual Studio 调试优化如何工作?
- 为什么开关的优化方式与 c/c++ 中的链接不同?
- 线性优化目标函数中的绝对值
- GCC 会优化内联访问器吗?
- gcc 如何优化此循环?
- 如何防止 CUDA-GDB 中的<优化输出>值
- 为什么我的程序在 O0 和 O2 的优化级别返回不同的结果
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 使用 std::p air 进行返回值优化