|
linux下 c语言调用c++的静态库或动态库。g++编译cpp 文件为库文件。编译C文件时gcc 要链接 -l stdc++ 这个库**(非常重要)
- //定义c++ class 头文件
- #ifndef REGEX_H
- #define REGEX_H
- class Regex
- {
- public:
- Regex();
- int add(int a,int b);
- };
- #endif // REGEX_H
复制代码- // class 头文件
- #include "regex.h"
- Regex::Regex()
- {
- }
- int Regex::add(int a,int b){
- return (a+b)*10;
- }
复制代码- //test.h 文件
- //对c语言提供对外按c语言编译的接口
- #ifndef TEST_H
- #define TEST_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- int test(int a,int b);
- #ifdef __cplusplus
- }
- #endif
- #endif // TEST_H
复制代码- //test.cpp
- //对外接口实现
- #include "test.h"
- #include"regex.h"
- #ifdef __cplusplus
- extern "C"{
- #endif
- int test(int a,int b)
- {
- Regex regex;
- return regex.add(a,b);
- }
- #ifdef __cplusplus
- }
- #endif
复制代码- //以上c++ 四个文件 编译成静态库或者动态库
- //gcc main.c -om -Iinclude -Laddr -llibname
- //C 语言测试文件
- #include<stdio.h>
- #include"./regex/test.h"
- int main(){
- int res=test(10,20);
- printf("res=%d\n",res);
- }
复制代码
|
|