C++常用的宏

#include <iostream>
#include <string>

// 用于演示 __VA_ARGS__ 的宏
#define LOG(...) printf("[LOG] " __VA_ARGS__)

// 演示 __COUNTER__ 的用法
#define CREATE_UNIQUE_NAME(name) name##__COUNTER__

// C++20 的 source_location 示例(需要 C++20)
#if __cplusplus >= 202002L
#include <source_location>
void demo_source_location(
    const std::source_location loc = std::source_location::current()) {
    std::cout << "\n[C++20 source_location]\n"
              << "File: " << loc.file_name() << '\n'
              << "Line: " << loc.line() << '\n'
              << "Function: " << loc.function_name() << std::endl;
}
#endif

void demo() {
    std::cout << "=== Standard Macros ===\n";
    std::cout << "__LINE__:         " << __LINE__ << '\n';
    std::cout << "__FILE__:         " << __FILE__ << '\n';
    std::cout << "__DATE__:         " << __DATE__ << '\n';
    std::cout << "__TIME__:         " << __TIME__ << '\n';
    std::cout << "__cplusplus:      " << __cplusplus << '\n';
    std::cout << "__func__:         " << __func__ << '\n';

    std::cout << "\n=== Compiler Extensions ===\n";
    
    // GCC/Clang 扩展
    #if defined(__GNUC__) || defined(__clang__)
    std::cout << "__FUNCTION__:     " << __FUNCTION__ << '\n';
    std::cout << "__PRETTY_FUNCTION__: " << __PRETTY_FUNCTION__ << '\n';
    std::cout << "__COUNTER__:      " << __COUNTER__ << '\n';
    std::cout << "__COUNTER__ again: " << __COUNTER__ << '\n';
    std::cout << "__INCLUDE_LEVEL__: " << __INCLUDE_LEVEL__ << '\n';
    #endif

    // MSVC 扩展
    #if defined(_MSC_VER)
    std::cout << "__FUNCSIG__:      " << __FUNCSIG__ << '\n';
    std::cout << "__FUNCDNAME__:    " << __FUNCDNAME__ << '\n';
    #endif

    // 其他
    #ifdef __STDC_VERSION__
    std::cout << "__STDC_VERSION__: " << __STDC_VERSION__ << '\n';
    #endif
    
    #ifdef __TIMESTAMP__
    std::cout << "__TIMESTAMP__:    " << __TIMESTAMP__ << '\n';
    #endif

    // 演示 __VA_ARGS__
    LOG("This is a log message at line %d\n", __LINE__);

    // 演示 __COUNTER__
    int CREATE_UNIQUE_NAME(var) = 42; // 生成类似 var__0, var__1
}

int main() {
    demo();
    
    #if __cplusplus >= 202002L
    demo_source_location();
    #endif
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值