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

1. 原始代码

// demo2.h
#include 

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 

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

你可能感兴趣的:(c++,c语言,开发语言)