c 语言头文件和源文件 |
您所在的位置:网站首页 › 头文件和源文件是什么 › c 语言头文件和源文件 |
总结: 头文件和源程序h结尾的就是头文件,c结尾的就是源文件 把定义和实现分开,就可以通过头文件和源程序分开在头文件中去定义,在源文件中去实现,然后main方法包含的时候只要包含头文件就可以了。
0:实际项目当中可能由成千上万个源文件,大型项目中会按照不同饿模块氛围多个源文件,例如由客户,订单,商品,购物车等模块,那么就可以按照这些某块定义不同的源文件 讲程序按照模块定义在不同的源文件中,随之而来的问题是,不同文件之间如何共享函数和全局变量。
这里就有了头文件和源文件的划分了。 我们将需要共享的函数,外部变量和一些宏定义声明在头文件中,头文件一般以h结尾, 将定义(其实就是实现)写在源文件中,源文件一般以c结尾的文件。 当不同源文件之间需要共享函数或者变量是偶,可以通过#include 包含指令包含头文件即可 1: 创建头文件的步骤: 将定义(其实就是实现)写在源文件中,源文件一般以c结尾的文件。 当不同源文件之间需要共享函数或者变量是偶,可以通过#include 包含指令包含头文件即可 1: 创建头文件的步骤: 点击File->New->File..选择Header File->取名为Global 然后默认的:防止重复包含的 #ifndef Global_h #define Global_h #endif /* Global_h */ 2: 创建源文件的步骤: 点击File->New->File..选择C File->取名为Global 3: 如果有一个变量在两个头文件中都进行了宏定义了,那么会采用后来的哪个的值
head1.h: #ifndef head1_h #define head1_h #define TRUE 1 #define FALSE 0 #endif /* head1_h */head2.h #ifndef head2_h #define head2_h #define TRUE 2 #define FALSE 0 #endif /* head2_h */main.c #include #include "head2.h" #include "head1.h" int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); printf("TRUE=%d\n",TRUE); return 0; } 运行结果: Hello, World! TRUE=1 Program ended with exit code: 0 4: 这里需要强调的是声明,例如int a;在前面我们并没有区分声明合定哦,其实变量的声明合定义是截然不同的。 变量的声明并不分配内存空间,而定义是要分配内存空间。 要想实现声明,我们要用到另外一个关键字extern,该关键字表明只声明变量,变量的定义可能在其他的源文件中。 例如 extern int a; 5: 头文件的嵌套,头文件中可以包含其他的头文件,看看stdio.h里面其实也包含了其他的头文件 6: 构建一个购物商城: 其实就是简单一点,在h文件中申明,在c文件中定义实现,然后在main中只要倒入h文件就可以了,然后就可以直接使用了 只放一个例子: global.h // // global.h // Market // // Created by 千 on 16/7/24. // Copyright © 2016年 kodulf. All rights reserved. // #ifndef global_h #define global_h typedef struct{ int cid; char name[20]; int age; } Customer; typedef struct{ int oid; char name[20]; } Order; #endif /* global_h */ 创建Customer.c的文件,其实创建的时候就帮忙把h文件创建好了Customer.h // // Customer.h // Market // // Created by 千 on 16/7/24. // Copyright © 2016年 kodulf. All rights reserved. // #ifndef Customer_h #define Customer_h #include void buy(); void clogin(); #endif /* Customer_h */ Customer.c // // Customer.c // Market // // Created by 千 on 16/7/24. // Copyright © 2016年 kodulf. All rights reserved. // #include "Customer.h" void buy(){ printf("客户购买了\n"); } void clogin(){ printf("登陆了\n"); }main.c // // main.c // Market // // Created by 千 on 16/7/24. // Copyright © 2016年 kodulf. All rights reserved. // #include //商品 Product //客户 Customer //订单 Order //购物车 ShoppingCart #include "Customer.h" #include "Product.h" #include "Order.h" #include "Cart.h" #include "global.h" int main(int argc, const char * argv[]) { // insert code here... productIn(); productOut(); clogin(); buy(); add(); del(); js(); del(); Customer c; c.cid = 1001; strcpy(c.name,"tom"); c.age=20; return 0; }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |