C/C++跨文件调用函数
C项目跨文件调用函数需要写相应的头文件来实现调用,下面是一个简单的例子来解释C项目文件跨文件调用函数。
sort.c
#include "sort.h"
#include "stdio.h"
void bubble(int a[])
{
int i, j, t;
n=5;
for(i=1; i<n; i++)
for(j=0; j<n-i; j++)
if(a[j]>a[j+1]) {
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
sort.h
#ifndef _SORT_H
#define _SORT_H //防止重复引用
#include <stdio.h>
void bubble (int a[]);
//or del this sentence condition ①
int n;
#endif
main.c
#include "sort.h"
extern void bubble (int a[]);
//or void bubble (int a[]); condition ①
main()
{
int i, a[10]={4,2,5,1,3};
bubble(a);
printf("After sorted = ");
for (i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n");
test();
}
C/C++项目内部.c文件和.cpp文件跨文件调用函数的方式同C项目调用,但cpp文件到c文件需要告诉编译器把需要调用的函数需要用C编译,例子如下:
sort.c
#include "sort.h"
#include "stdio.h"
void bubble(int a[])
{
int i, j, t;
n=5;
for(i=1; i<n; i++)
for(j=0; j<n-i; j++)
if(a[j]>a[j+1]) {
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
sort.h
#ifndef _SORT_H
#define _SORT_H //防止重复引用
#include <stdio.h>
void bubble (int a[]);
//or del this sentence condition ①
int n;
#endif
test.cpp
#include "stdio.h"
#include "sort.h"
extern "C" int test(void)//告诉编译器编译成C文件可识别
{
printf("Hello, I am test.cpp\n");
return 0;
}
test.h
#ifndef _TEST_H
#define _TEST_H //防止重复引用
int test(void);
#endif
main.c
#include "sort.h"
#include "test.h"
extern void bubble (int a[]);
main()
{
int i, a[10]={4,2,5,1,3};
bubble(a);
printf("After sorted = ");
for (i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n");
test();
}