C与C++混合编程、编译

1. 工程文件架构

drwxrwxr-x 3 JoshYoby JoshYoby 4096 2月  25 15:03 ./
drwxrwxr-x 8 JoshYoby JoshYoby 4096 2月  25 14:45 ../
-rw-rw-r-- 1 JoshYoby JoshYoby  671 2月  25 14:58 Makefile
-rw-rw-r-- 1 JoshYoby JoshYoby  168 2月  25 14:57 my_main.cpp
drwxrwxr-x 2 JoshYoby JoshYoby 4096 2月  25 14:49 temp/
-rw-rw-r-- 1 JoshYoby JoshYoby   67 2月  25 14:54 test.c
-rw-rw-r-- 1 JoshYoby JoshYoby   66 2月  25 14:54 test.h
-rw-rw-r-- 1 JoshYoby JoshYoby  158 2月  25 14:48 tools.cpp
-rw-rw-r-- 1 JoshYoby JoshYoby  188 2月  25 14:42 tools.h

temp目录下只有一个 my_main.c 文件


2. test.c 内容

#include "test.h"

int testAdd(int a, int b)
{
	return (a + b);
}


3. test.h 内容

#ifndef TEST_H
#define TEST_H

int testAdd(int a, int b);

#endif

4. tools.cpp 内容

#include "tools.h"
#ifdef __cplusplus
extern "C"
{
#endif

using namespace std;

void toolsHello()
{
	cout<<"hello world\n"<<endl;
}

#ifdef __cplusplus
}
#endif


5. tools.h 内容

#ifndef TOOLS_H
#define TOOLS_H

#ifdef __cplusplus
#include <iostream>
#include <time.h>
#endif

#ifdef __cplusplus
extern "C"{
#endif

void toolsHello();

#ifdef __cplusplus
}
#endif

#endif

6. my_main.cpp文件内容
这里展示了如何在.cpp文件中调用.c文件中的函数。

#include <iostream>
#include "tools.h"

extern "C"
{
	#include "test.h"
}

using namespace std;

int main()
{
	toolsHello();
	cout << "1 + 2 = " << testAdd(1, 2) <<endl;
}


7. temp/my_main.c文件内容
这里展示了在.c文件中调用.cpp中的函数,前提是.cpp文件中的函数均像tools.cpp一样的写法。

#include <stdio.h>
#include <stdlib.h>
#include "tools.h"
#include "test.h"

int main()
{
	toolsHello();
	printf("1 + 2 = %d\n", testAdd(1, 2));
}


8. Makefile文件内容

#指定编译工具
CC = gcc
CPP = g++
LINK = g++
 
LIBS = -lpthread
#编译.so 必须添加 -fPIC 和 -shared 选项  
CCFLAGS = -c -g -fPIC
CPPFLAGS = -c -g -fPIC

#期望得到的执行文件或动态库.so
#TARGET=libxx.so
TARGET=test
 
INCLUDES = -I. #-I../../
 
CPPFILES = $(wildcard *.cpp ../*.cpp)#遍历得到当前目录及上层目录中的所有.cpp文件
CFILES = $(wildcard *.c ../*.c)#遍历得到当前目录及上层目录中的所有.c文件
 
OBJFILE = $(CFILES:.c=.o) $(CPPFILES:.cpp=.o)
 
all:$(TARGET)
 
$(TARGET): $(OBJFILE)
# 编译得到 .so 文件用下面的代码
#	$(LINK) $^ $(LIBS) -Wall -fPIC -shared -o $@
# 编译得到可执行文件用下面的代码
	$(LINK) $^ $(LIBS) -Wall -O2 -o $@

%.o:%.c
	$(CC) -o $@ $(CCFLAGS) $< $(INCLUDES)
 
%.o:%.cpp
	$(CPP) -o $@ $(CPPFLAGS) $< $(INCLUDES)
 
clean:
	rm -rf $(TARGET)
	rm -rf $(OBJFILE)

符号解释:
$@----表示目标文件

$^----表示所的依赖文件

$<----表示所依赖的当前这一个文件
在当前工程目录下,打开终端窗口,输入 make 命令即可得到 test可执行文件。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值