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); }

 

 

 

 

posted @ 2019-03-03 02:09  ForMeDream  阅读(2437)  评论(0编辑  收藏  举报