C/C++预编译阶段获得sizeof(xx)的值

譬如目标平台是arm的板子,arm-none-eabi-g++作为编译器。手头没有板子来运行代码,而代码中又需要确定sizeof(xx)的值。如下代码包含了两种方法。

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <stdint.h>

//方法1:用warning搞
//https://stackoverflow.com/questions/20979565/how-can-i-print-the-result-of-sizeof-at-compile-time-in-c
char (*__kaboom)[sizeof( int* )] = 1;  //改成你需要的类型
char (*__kaboom)[sizeof( int32_t* )] = 1;


//方法2,用C++的模板参数搞。来自xfan
#include <cstddef>
template <std::size_t x>
struct show_size;

void foo()
{
    show_size<sizeof(char)>(); //改成你需要的类型
}

using namespace std;

int main() {

        cout << "hello " << endl;

        return 0;
}

原文链接: https://www.cnblogs.com/zjutzz/p/13398197.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C/C++预编译阶段获得sizeof(xx)的值

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200913

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:36
下一篇 2023年2月12日 下午8:36

相关推荐