C++----------extern “C“ 用法

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的静态库 

 

 

 现在就可以编译.cpp文件了。

在c中编译c++的静态库

 现在就可以在.c中编译了

 

我们只要记住extern "C" 是C++中才能使用的,为什么用 extern "C"可以编译不同的语言的文件,这里是函数修饰规则改变,在编译链接时在符号表找函数地址时可以找到,不用extern "C"c语言的c++语言的函数修饰规则时不一样的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值