C++中如何调用C代码

背景:为什么会在C++代码中调用C代码

  1. 与状态机交互的时候,状态机模型在matlab中生成的是C代码
  2. 拿到别的团队开放的三方库,对应的头文件和接口也是C代码

C++中要使调用C函数会出现函数未定义的错误
要想不报错(未定义错误)其实很简单,只需要两步:
1> 使用extern “C” 对原C文件的头文件进行修改
例如:
原C文件的头文件:

#ifndef LIST_H
#define LIST_H

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

#endif // LIST_H

修改后的头文件:

#ifndef LIST_H
#define LIST_H

#ifdef __cplusplus
extern "C" {
    
    
#endif

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#ifdef __cplusplus
}
#endif

#endif // LIST_H

2> 对在cpp头文件中的引用#include的格式进行修改
例如:

原引用:

#include"list.h"

修改后的引用:

extern "C" {
    
    
#include"list.h"
}

猜你喜欢

转载自blog.csdn.net/weixin_42445727/article/details/129026677