首先extern “C”应该是用c语言编译器解释函数底层名字,那么请看下列代码:
/*Demo.h*/
#ifndef _DEMO_H_
#define _DEMO_H_
#ifdef __cplusplus
extern "C" {
#endif
extern int a;
extern int b;
int add(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
=============================
/*Demo.c*/
#include "Demo.h" //
/*如果这里不注释,那么g++ main.cpp Demo.c 都是经由c++编译器操作的,但是extern “c”不是代表用c编译器的规则去翻译函数吗?为啥还是能通过编译并正确执行,明明add函数的声明都是加了extern "c"的.*/
/*特别说明(我自己试验的),g++ main.cpp Demo.c等于下列命令
g++ -c main.cpp
g++ -c Demo.c
g++ main.o Demo.o
*/
#include <stdio.h> //
int a = 10;
int b = 20;
int add(int l, int r)
{
#ifndef __cplusplus
printf("这是一个c程序!\n");
#endif // !_cplusplus
#ifdef __cplusplus
printf("这是一个c++程序!\n");
#endif // !_cplusplus
return l + r;
}
=====================
/*main.cpp*/
#include "Demo.h"
#include <iostream>
using namespace std;
void main()
{
#ifdef __cplusplus
cout << "这是一个c++程序" << endl;
#endif
#ifndef __cplusplus
cout << "这是一个c程序" << endl;
#endif
cout << "a = " << a << ", b = " << b << endl;
int c = add(1, 2);
printf("c = 1 + 2 = %d \n", c);
}
召唤大佬!!!求帮助,谢谢!