stack.h
/*
* Copyright (C) 2019 0.1gCode
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is stack
*/
#ifndef _STACK_H
#define _STACK_H
#include <stddef.h>
/*
*声明 extern "C"就是要告诉编译器该函数是C函数,确保C++可以调用
*前后夹着的#ifdef __cplusplus是为了告诉编译器,extern "C"仅在C++中编译时有效
*/
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int top;
const size_t size;
int *const pBuf;
}Stack;
/*在头文件中公开未使用static修饰的函数*/
bool push(Stack *p, int val);
bool pop(Stack *p,int *pRet);
/*使用宏定义初始化结构体*/
#define newStack(buf){ \
0, \
sizeof(buf)/sizeof(int), \
(buf) \
}
#ifdef __cplusplus
}
#endif
#endif
stack.c
/*
* mywork/mode/disign_mode/00_c_module/stack.c
*
* Copyright (C) 2019 0.1gCode
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is stack
*
*/
#include <stdbool.h>
#include "stack.h"
/*
*C常用模块化方法:
*在函数名或变量名前使用static修饰符,使函数或变量只在改变以单位内有效,可以有效避免名称冲突;
*在头文件中公开未使用static修饰的函数,其他不需要公开的函数或变量使用static修饰;
*/
static int buf[16];
static int top = 0;
static bool isStackFull(const Stack *p)
{
return p->top == p->size;
}
static bool isStackEmpty(const Stack *p)
{
return p->top == 0;
}
/*true:成功 , false:失败*/
bool push(Stack *p,int val)
{
if(isStackFull(p)){
return false;
}
p->pBuf[p->top++] = val;
return true;
}
/*true:成功 , false:失败*/
bool push(Stack *p,int *pRet)
{
if(isStackEmpty)
{
return false;
}
*pRet = p->pBuf[--p->top];
return true;
}
#使用方法
int buf[16];
Stack stack = newStack(buf);
#newStack宏展开如下:
Stack stack = {0,sizeof(buf)/sizeof(int),(buf)};