C/C++ 使用 define 实现运行时函数是在哪个文件哪个函数被调用

1. 原始代码

// demo2.h
#include <iostream>

void testFunc(int num)
{
    std::cout << num << std::endl;
}
//main.cc
#include "demo2.h"

void func1()
{ }

void func2()
{
    testFunc(24);
}

int main()
{
    func1();
    func2();

    return 0;
}
  • 我现在需要知道 testFunc 是在哪一行被调用了。

2. 使用 define 实现

#include <iostream>

#define testFunc(num) __testFunc(num, __FILE__, __FUNCTION__, __LINE__)

void __testFunc(int num, const char* fileName, const char* funcName, int line)
{
    std::cout << fileName << std::endl;
    std::cout << funcName << "()" << std::endl;
    std::cout << "line: " << line << std::endl;
    std::cout << num << std::endl;
}
  • 主函数一样
#include "demo2.h"

void func1()
{ }

void func2()
{
    testFunc(24);
}

int main()
{
    func1();
    func2();
    return 0;
}
如此就实现了打印函数在娜个文件、哪个函数哪一行被调用的效果

作为 debug 的时候很有用,比如下面的代码:

#include <stdio.h>

/**
 * @brief 支持预定义标识符
 * 
        __FILE__  :    表示进行编译的源文件字符串
        __FUNCTION__ :  表示所在函数
        __LINE__ :     表示当前文件的行号
        __DATE__:      表示文件日期
        __TIME__ :     表示文件时间
 */

#define DEBUG_LOG(fmt, args...)                                    \
    do                                                               \
    {                                                                \
        printf("[debug]  %s:%d func: %s(): ", __FILE__, __LINE__, __FUNCTION__); \
        printf(fmt, ##args);                                         \
    } while (0)

void print_str(const char* pStr)
{
    if (NULL == pStr)
    {
        DEBUG_LOG("pStr is NULL\n");
        return;
    }

    printf("%s\n", pStr);
}

int main()
{
    // [debug] func: print_str() line25 pStr is NULL
    print_str(NULL);    // 在这里,它传进一个 NULL,非法,会在函数内部报错,但是我们又想知道是哪一行报的错,__LINE__ 和 __FUNCTION__ 就非常有用

    // 小小滴熊
    print_str("小小滴熊");

    return 0;
}

输出:

[debug] func: print_str() line25 pStr is NULL
小小滴熊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值