请原谅我,如果这听起来是一个多次被问过的问题,但我向你保证这有点不同.
我使用Codeblocks进行C编程,最近我开始想知道为什么有人在C中使用头文件.我理解它用于声明和/或定义变量结构.但这是我尝试过的东西,现在我很困惑.
我有一个名为的头文件
test1.h
#ifndef TEST1_H_INCLUDED
#define TEST1_H_INCLUDED
static int testvar = 233;
extern int one;
extern void show();
#endif // TEST1_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)
和另外两个文件
headertest.c
#include"test1.h"
#include<stdio.h>
int one = 232;
int main()
{
testvar = 12;
printf("The address of one is %p and value is %d",&testvar,testvar);
printf("value of one is %d",one);
show();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
headertest2.c
#include "test1.h"
#include<stdio.h>
extern int one;
extern void show()
{
//extern int one;
testvar = 34;
printf("\nThe address of one is %p and value …Run Code Online (Sandbox Code Playgroud) 1)在C和C++中,static,extern和const及其使用有何不同?(默认链接和其他差异)
2)在C中使用的头文件中允许以下声明和定义,然后将其包含在多个文件中.
static int testvar = 233;
extern int one;
extern int show();
int abc;
const int xyz; // const int xyz = 123; produces error
Run Code Online (Sandbox Code Playgroud)
const 定义在编译期间产生和错误(可能是因为多个定义).但是我可以在头文件中声明一个const变量,但是因为我们可以定义它提供一个值,我们也不能在这个头包含的文件中分配一个值,它实际上是没用的.有没有办法在头文件中定义const,然后通过包含标题在多个文件中访问它?
3)需要做哪些更改(如果有的话),以便此标头可以包含在C++中的多个文件中?
4)考虑以下内容
header.h
static int z = 23;
Run Code Online (Sandbox Code Playgroud)
test.c的
#include"header.h"
z = 33; //gives error redefinition of z!!!??
void abc()
{
z = 33; //perfectly fine here!!??
}
Run Code Online (Sandbox Code Playgroud)
标头中定义/声明的静态变量在每个文件中都有内部链接意味着每个文件都有一个单独的变量副本.那么为什么在任何函数之外为该var赋值给出重定义错误,而它是函数内的完美文件?
编辑:添加了第4个问题.这非常令人困惑.
**PS:现在我只在寻找问题1和4的答案.