相似 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_*函数的不断运行,一条链表就产生了。

看起来就像是用全局变量组成了一条单项链表。

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

原文地址:https://www.cnblogs.com/clnchanpin/p/6915985.html