类似 nginx 编译时生成函数链表


以下代码可能需要一定的c/c++基础。

需要有一些函数指针的知识

深度剖析函数指针点击这里


common.h

#pragma once
typedef int (*pt)(void);
void init_2();

2.cpp

#include <iostream>
#include "common.h"
using namespace std;
static pt next_pt;
extern pt top_pt;
int filter_2()
{
    cout<<"filter_2"<<endl;
    if(next_pt)
        next_pt();
}
static void filter_2_init()
{
    next_pt = top_pt;
    top_pt = filter_2; 
}
void init_2()
{
    filter_2_init();
}
 1.cpp

#include <iostream>
#include "common.h"
using namespace std;
static pt next_pt;
pt top_pt;

static int filter_1()
{
    cout<<"filter_1"<<endl;    
    if(next_pt)
        next_pt();
}
static void filter_init()
{
    next_pt = top_pt;
    top_pt = filter_1;
}
void init_1()
{
    filter_init();
}
int main()
{
    init_1();
    init_2();
    top_pt();
    return 0;
}


编译命令 

g++ 1.cpp 2.cpp -g -O0

执行

./a.out

filter_2
filter_1

如果你已经编程并执行成功,请继续往下看.

top_pt 为全局变量

next_pt为局部全局变量

如果你想知道

top_pt 在每次代码执行时都会变化,不断地指向新的链表头部,通过init_*函数的不断执行,一条链表就产生了。看起来就像是用全局变量组成了一条单项链表。

好吧,又是奇淫技巧,如是而已!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值