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

1. 原始代码

cpp 复制代码
// demo2.h
#include <iostream>

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

void func1()
{ }

void func2()
{
    testFunc(24);
}

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

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

2. 使用 define 实现

cpp 复制代码
#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;
}
  • 主函数一样
cpp 复制代码
#include "demo2.h"

void func1()
{ }

void func2()
{
    testFunc(24);
}

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

作为 debug 的时候很有用。

相关推荐
嗑嗑嗑瓜子的猫6 分钟前
Java!它值得!
java·开发语言
xiaoshuaishuai830 分钟前
C# GPU算力与管理
开发语言·windows·c#
lsx20240637 分钟前
SVN 创建版本库
开发语言
xiaotao13140 分钟前
01-编程基础与数学基石:Python错误与异常处理
开发语言·人工智能·python
墨尘笔尖1 小时前
最大最小值降采样算法的优化
c++·算法
glimix1 小时前
Word-Pop:使用C语言开发打单词游戏
c语言·游戏
皮卡蛋炒饭.1 小时前
线程的概念和控制
java·开发语言·jvm
John.Lewis1 小时前
Python小课(1)认识Python
开发语言·python
一只大袋鼠2 小时前
MyBatis 入门详细实战教程(一):从环境搭建到查询运行
java·开发语言·数据库·mysql·mybatis
sonnet-10292 小时前
函数式接口和方法引用
java·开发语言·笔记