孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

首先我们看一个例子

新建一C++控制台工程,代码结构如下:

test.h代码如下

#pragma once
#include <stdio.h>

void show();

test.c代码如下

#include "test.h"

void show()
{
	printf("hello world!\n");
}

ConsoleApplication5.cpp代码如下

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "test.h"

int main()
{
    show();
    system("pause");
    return EXIT_SUCCESS;
}

编译代码报错,找不到函数定义
此处因为调用C语言的函数,所以应该使用extern进行声明,安装C语言进行函数的编译
ConsoleApplication5.cpp修改为

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//#include "test.h"

//C++中调用C语言方法
extern "C" void show();

int main()
{
    show();
    system("pause");
    return EXIT_SUCCESS;
}

就可以编译通过了,如果有多个C语言的函数需要调用,则可以直接修改test.h代码为:

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <stdio.h>
void show();

#ifdef __cplusplus
}
#endif

然后将ConsoleApplication5.cpp改为

// ConsoleApplication5.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "test.h"

//C++中调用C语言方法
//extern "C" void show();

int main()
{
    show();
    system("pause");
    return EXIT_SUCCESS;
}
posted on 2021-10-12 14:17  孤独的猫  阅读(636)  评论(0编辑  收藏  举报