如何让编译器捕获两个C源文件中全局变量类型不一致的问题

发布于 2025-01-10 16:12:53 字数 344 浏览 2 评论 0原文

my1.c

extern float e;
void f1(){ e=3.0;}

my2.c

#include <stdio.h>
int e=0;
void f1();
void main(){
  printf("%d in main \n", e);
  f1();
  printf("%d in main \n", e);
}

这里全局变量e在两个源文件中被错误地声明为floatint

如何让链接器因这种不一致而引发错误?

my1.c

extern float e;
void f1(){ e=3.0;}

my2.c

#include <stdio.h>
int e=0;
void f1();
void main(){
  printf("%d in main \n", e);
  f1();
  printf("%d in main \n", e);
}

Here the global variable e is mistakenly declared as float and int in two source files.

How to let the linker raise error for this inconsistency?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不如归去 2025-01-17 16:12:53

我们使用头文件而不是链接器来减轻这种风险。多个翻译单元中引用的任何内容都应在一个头文件中声明:

MyGlobal.h:

extern float e;

任何使用它的文件都应包含头文件:

main.c:

#include "MyGlobal.h"

…
    printf("e is %f.\n", e);

只有一个文件应定义它,并包含头文件:

MyGlobal.c :

#include "MyGlobal.h"

float e = 0;

通过使用头文件,所有翻译单元中的声明都是相同的。由于定义标识符的源文件还包括头文件,因此编译器会报告任何不一致。

头文件之外的任何外部声明(不是定义)都是可疑的,应该避免。

We mitigate this risk using header files, not the linker. Anything referred to in multiple translation units should be declared in one header file:

MyGlobal.h:

extern float e;

Any file that uses it should include the header file:

main.c:

#include "MyGlobal.h"

…
    printf("e is %f.\n", e);

Exactly one file should define it, and include the header file:

MyGlobal.c:

#include "MyGlobal.h"

float e = 0;

By using a header file, the declaration is identical in all translation units. Because the source file that defines the identifier also includes the header file, the compiler reports any inconsistency.

Any external declarations (that are not definitions) outside of header files are suspect and should be avoided.

2025-01-17 16:12:53

1.c

static float e;
void f1(){ e=3.0;} 

2.c

#include <stdio.h>
static int e=0;
void f1();
void main()
{
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}

1.c

static float e;
void f1(){ e=3.0;} 

2.c

#include <stdio.h>
static int e=0;
void f1();
void main()
{
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文