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