C++中使用C

定義一個c的頭文件

1
2
//定義一個c函式
void test(int x, int y);

實作頭文件

1
2
3
4
5
6
7
#include <stdio.h>
#include "a.h"

//實作頭文件定義的c函式
void test(int x, int y){
    printf("x=%d, y=%d\n", x, y);
}

C++檔案中使用C

在頭文件引入的部分要用extern "C"{}包起來,因為這是C的程式

1
2
3
4
5
6
7
#include <iostream>
extern "C"{
#include "a.h"
}
int main() {
    test(1,2);
}

執行結果

x=1, y=2

也可以直接由頭文件判斷是否是在c++的環境中,透過__cplusplus的宏定義,若是在c++的環境,就要加上extern “C”{}

1
2
3
4
5
6
7
8
#ifdef __cplusplus
extern "C" {
#endif
//定義一個c函式
void test(int x, int y);
#ifdef __cplusplus
}
#endif

在main.cpp就不用再判斷extern “C”{}

1
2
3
4
5
#include <iostream>
#include "a.h"
int main() {
    test(1,2);
}

results matching ""

    No results matching ""