C&C++跨文件调用

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();
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值