c++调用 c 接口

定义 c 接口

1
2
3
4
5
6
7
8
// hello.c
#include "hello.h"

void helloworld()
{
    printf("Hello World\n");
    return;
}

编译 c 生成 object 文件

1
gcc -c hello.c

定义头文件 hello.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>

#ifdef __cplusplus
extern "C"
{
#endif
    // 导出函数库
    void helloworld();

#ifdef __cplusplus
}
#endif
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// main.c
#include "hello.h"

int main(void)
{

    helloworld();

    return 0;
}

编译 c

1
2
3
gcc -o main.exe main.c hello.o

main.exe //执行结果 Hello World

编写 c++代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//main.cpp
#include "hello.h"
#include <iostream>

using namespace std;

int main(void)
{
    cout << "c function start" << endl;
    helloworld();
    cout << "c function end" << endl;
    return 0;
}

编译 c++代码

1
2
3
g++ -o main.exe main.cpp hello.o

main.exe
1
g++ -E main.cpp -o  main.i

Makefile 文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
C_SRCS=hello.c
C_MAIN=main.cpp
# 将main.cpp字符串换成main.exe
TARGET=$(C_MAIN:.cpp=.exe)

# $@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件
${TARGET}: ${C_MAIN} hello.o
	g++ -o $@ $^
	# gcc -o $@ $^

hello.o:
	gcc -c ${C_SRCS}

run: ${TARGET}
	./${TARGET}

.PHONY: clean
clean:
	rm -rf *.o *.exe