C++和C中的翻译单元之间有区别吗?
在其他帖子中,我读到标题和源文件构成了一个翻译单元,但是单独的源文件可以在C++中被称为翻译单元,其中它包含一个文件中的所有定义吗?
我是C的新手.我面前有一本书,解释了C的"文件范围",包括示例代码.但是代码只声明并初始化一个文件范围的变量 - 它不会通过尝试以非法方式访问它来验证变量的范围.所以!本着科学的精神,我构建了一个实验.
档案bar.c:
static char fileScopedVariable[] = "asdf";
Run Code Online (Sandbox Code Playgroud)
档案foo.c:
#include <stdio.h>
#include "bar.c"
main()
{
printf("%s\n", fileScopedVariable);
}
Run Code Online (Sandbox Code Playgroud)
根据我的书和谷歌,呼叫printf()应该失败 - 但事实并非如此.foo.exe输出字符串"asdf"并正常终止.我非常想使用文件范围.我错过了什么?
在C语言中,我想访问文件范围之外的全局静态变量.让我知道最好的方法.其中一种方法是为外部全局变量赋值静态变量的值,
在档案中
static int val = 10;
globalvar = val;
Run Code Online (Sandbox Code Playgroud)
在文件bc中
extern globalvar;
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,val(文件ac)中的任何更改都不会在(文件bc)中的globalvar中更新.
请让我知道如何实现同样的目标.
谢谢,Sikandar.
以下代码“正确”吗?或者它会是未定义的行为?
// myfile.c
static char x[10][10];
char* my_function() {
return x[0];
}
Run Code Online (Sandbox Code Playgroud)
my_function正在共享库中使用,所以我认为在文件/编译单元之外访问它的返回值是不安全的(由于static关键字)。
我怎么能从另一个文件访问静态变量?静态变量不具有文件范围吗?
bash-3.2$ ls
a.c b.c
bash-3.2$ cat a.c
#include <stdio.h>
static int s = 100;
int fn()
{
/* some code */
}
bash-3.2$ cat b.c
#include <stdio.h>
#include "a.c"
extern int s;
int main()
{
printf("s = %d \n",s);
return 0;
}
bash-3.2$ gcc b.c
bash-3.2$ a.exe
s = 100
Run Code Online (Sandbox Code Playgroud)