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 的时候很有用。

相关推荐
RuoZoe20 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
祈安_4 天前
C语言内存函数
c语言·后端
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端