c++和c混編

c主程序調用c++函數,如本示例中的init()。
c++函數中又訪問c中的變量,如本示例中的infoget(),訪問了c中的變量a。
c++函數中又訪問c中的函數,如本示例中的testget(),調用了c中的geta()。

  • 概述
示例代碼目錄:
[root@localhost ccc]# tree
.
├── a.out
├── build.sh
├── foo.c
├── foo.h
├── main.c
├── num.c
└── rpc.cc

編譯:
./build.sh

測試:
[root@localhost ccc]# ./a.out    
c main a_local[100]
c main geta[100]
c main seta to 5
c main a_local[5]
c main geta[5]

HelloWorld
cc info get 5
cc info set 5 to 600

cc get a 600
cc set a 2
c main a_local[2]
c main geta[2]

  • main.c
#include <stdio.h>

#include "foo.h"

extern int a;
extern void init();
extern void infoget();
extern void infoset(int);
extern void testset(int);
extern int testget();

int main()
{
        // call c 
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n", geta());
        printf("c main seta to 5\n", seta(5));
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n\n", geta());

        //call c++ val 
        init();
        infoget();
        infoset(600);
        printf("\n");

        //call c++ func 
        testget();
        testset(2);
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n", geta());
}
  • foo.h
#ifdef __cplusplus
extern "C" {
#endif 

extern int a;

int geta();
int seta(int);

#ifdef __cplusplus  
}  
#endif

  • foo.c
#include "foo.h"


int geta() {
    return a;
}

int seta(int v) {
    a=v;
}
  • num.c
int a= 100;
#include <iostream>

#include "foo.h"

extern "C" int testget();
extern "C" void testset(int);
extern "C" void init();
extern "C" void infoget();
extern "C" void infoset(int);

using namespace std;

void infoget()
{
    cout << "cc info get ";
    cout << a << endl;
}

void infoset(int v)
{
    cout << "cc info set ";
    cout << a ;
    a = v;
    cout << " to ";
    cout << a  << endl;
}

int testget()
{
    int a;
    cout << "cc get a ";
    a = geta();
    cout << a << endl;
    return a;
}

void testset(int i)
{
    cout << "cc set a ";
    cout << i << endl;
    seta(i);
}

void init()
{
    cout << "HelloWorld" << endl;
}
#!/bin/sh
gcc main.c num.c foo.c rpc.cc  -lstdc++
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章