extern "C" 是C++调用c的静态库的关键,同时也可以让c去调用c++的静态库,这里我以力扣上一道括号匹配的题为线,先看原题
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本题思路是用栈遇到左括号入栈,遇到右括号看是否匹配,匹配出栈代码如下
先实现栈
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int StackDataType;
typedef struct stack
{
StackDataType* a;
int top;
int capatity;
}ST;
void InitStack(ST* pc);
void PushStack(ST* pc, StackDataType data);
void PopStack(ST* pc);
StackDataType TopStack(ST* pc);
bool EmptyStack(ST* pc);
void DestroyStack(ST* pc);
#include"stack.h"
void InitStack(ST* pc)
{
pc->a = NULL;
pc->top = 0;
pc->capatity = 0;
}
void PushStack(ST* pc, StackDataType data)
{
assert(pc);
if (pc->top == pc->capatity)
{
int newcapatiy = pc->capatity == 0 ? 4 : pc->capatity * 2;
StackDataType* tmp = (StackDataType*)realloc(pc->a, newcapatiy);
pc->a = tmp;
pc->capatity = newcapatiy;
}
pc->a[pc->top++] = data;
}
void PopStack(ST* pc)
{
assert(pc);
assert(pc->top > 0);
pc->top--;
}
StackDataType TopStack(ST* pc)
{
assert(pc);
assert(pc->top > 0);
return pc->a[pc->top - 1];
}
bool EmptyStack(ST* pc)
{
assert(pc);
return pc->top == 0;
}
void DestroyStack(ST* pc)
{
assert(pc);
free(pc->a);
pc->a = NULL;
}
bool isValid(char* s)
{
ST st;
InitStack(&st);
while (*s)
{
if (*s == '(' || *s == '[' || *s == '{')
{
PushStack(&st, *s);
}
else
{
if (EmptyStack(&st))
{
DestroyStack(&st);
return false;
}
StackDataType top = TopStack(&st);
PopStack(&st);
if ((*s == ')' && top != '(') ||
(*s == ']' && top != '[') ||
(*s == '}' && top != '{'))
{
DestroyStack(&st);
return false;
}
}
s++;
}
bool ret = EmptyStack(&st);
return ret;
}
下面我就要实现在C++里调用c库了,先在VS下创建静态库工程
我们需要删除掉系统为我们创建的文件,4个都要删除
右键单击,选中属性
现在就可以把我们写好的stack.h 和stack.c放在工程下,编译生成静态库文件,这里不需要主函数(main)因为不是可执行程序
这时我们写好的静态库文件就好了,可以在工程文件下Debug下看到stack.lib静态库文件,下面我们在cpp文件中只要包含下面步骤就可以在c++中运行c的静态库