酷!學園
精華區 => 拾人牙慧 => 主題作者是: 劍客 於 2002-02-08 12:11
-
使用外部函式時,使用 extern 宣告。但是如果所呼叫的函式與呼叫者本身的語言不同時,可以指定所呼叫的函式的編譯語言。
範例如下;使用時打 make ,編譯成扑|產生一個 sum 的執行檔。大家可以換成註解的宣告再make 一次看看有什麼差別。
// filename: main.c
#include
extern "C" int sum(int a, int b);
/*
* 錯誤的宣告
*
* extern int sum(int a, int b);
*/
int main(void){
cout << "Sum is : " << sum(3,5) << endl;
return 0;
}
// filename sum.c
#include
int a;
int b;
int sum(int a, int b){
return a+b;
}
# filename Makefile
all:
cc -c sum.c
c++ -o sum main.c sum.o
-
1. C ++ invoke C :
// cfun.c
#include <stdio.h>
void cfunc(num1, num2, res)
int num1, num2, *res;
{
printf("func: a = %d b = %d ptr c = %x\n",num1,num2,res);
*res=num1/num2;
printf("func: res = %d\n",*res);
}
//cppmain.cpp
extern "C" void cfunc(int n, int m, int *p);
#include <iostream.h>
void main()
{ int a,b,c;
a=8;
b=2;
cout << "main: a = "<<a<<" b = "<<b<<" ptr c = "<<&c<< endl;
cfunc(a,b,&c);
cout << "main: res = "<<c<<endl;
}
2. C invoke C++:
// cmain.c
extern void cpfunc(int a, int b, int *c);
#include <stdio.h>
void main()
{ int a,b,c;
a=8;
b=2;
printf("main: a = %d b = %d ptr c = %x\n",a,b,&c);
cpfunc(a,b,&c);
printf("main: res = %d\n",c);
}
//cppfunc.cpp
#include <iostream.h>
extern "C" void cpfunc(int num1,int num2,int *res)
{
cout << "func: a = "<<num1<<" b = "<<num2<<" ptr c ="<<res<<endl;
*res=num1/num2;
cout << "func: res = "<<res<<endl;
}
-
1. C++ invoke C:
// cfunc.c
#include <stdio.h>
void cfunc(alarm,res)
int alarm;
char **res;
{
int i;
printf("func: alarm = %d ptr c = %x\n",alarm,&res);
i = (alarm==0)?1:0;
switch(i){
case 1 : *res = "true";break;
case 0 :
default : *res = "false";break;
}
printf("func: res = %s\n",*res);
}
// cppmain.cpp
extern "C" void cfunc(int x, char **y);
#include <string.h>
#include <iostream.h>
void main()
{
char *str="";
int a;
char *c="test";
cout<<"Enter 0/1 : ";
cin>>a;
switch(a)
{
case 1 : str = "true";//strcpy(str,"true");
break;
case 0 :
default : str = "false";//strcpy(str,"false");
break;
}
cout << "main: alarm = "<<str<<" ptr c = "<<&c<< endl;
cfunc(a,&c);
cout << "main: res = "<<c<<endl;
}
2. C invoke C++ :
//cppfunc.cpp
#include <iostream.h>
extern "C" void cpfunc(int alarm,char** res)
{
int i;
cout<<"func: alarm = "<< alarm <<" ptr c = "<<&res<<endl;
i = (alarm==0)?1:0;
switch(i){
case 1 : *res = "true";break;
case 0 :
default : *res = "false";break;
}
cout<<"func: res = "<<*res<<endl;
}
// cmain.c
extern void cpfunc(int a, char** c);
#include <stdio.h>
void main()
{
char *str="";
int a;
char *c="test";
printf("Enter 0/1 : ");
scanf("%d",&a);
switch(a)
{
case 1 : str = "true";//strcpy(str,"true");
break;
case 0 :
default : str = "false";//strcpy(str,"false");
break;
}
printf("main: alarm = %s ptr c = %x\n",str,&c);
cpfunc(a,&c);
printf("main: res = %s\n",c);
}