我经历了以下问题:
上面的链接描述了如果我们在一个文件中定义全局变量并且没有指定extern关键字,则由于翻译单元,它们将在另一个源文件中可访问.
现在我已经file1.c定义了以下全局变量和函数:
int testVariable;
void testFunction()
{
printf ("Value of testVariable %d \n", testVariable);
}
Run Code Online (Sandbox Code Playgroud)
在file2.c有下面的代码
void main()
{
testVariable = 40;
testFunction();
}
Run Code Online (Sandbox Code Playgroud)
现在我要了 error: 'testVariable' undeclared (first use in this function) - 为什么?
注意:两个文件都使用makefile在同一程序中使用.
根据我的理解,函数和全局变量都有默认的外部链接.所以函数我们可以直接在另一个文件中使用它的名字,但变量不能为什么?
任何人都有想法吗?
编辑:
从下面的答案我得到的想法,就像在函数旧的编译器将猜测并添加一个隐式声明,但在变量的情况下,它不能.此外,C99删除了隐式声明但仍然在C99模式下收到警告,如:
warning: implicit declaration of function ‘testFunction’.
Run Code Online (Sandbox Code Playgroud)
现在已经通过以下链接:
它说编译器将其作为诊断目的而不是出错.所以编译器可以向前处理.
但为什么在变量的情况下它无法进一步处理?即使在函数的情况下,如果编译器继续进行,如果实际的定义不存在,那么在链接时它将失败.那么前进有什么好处?
嗨,我有以下程序
#include <stdio.h>
#include <string.h>
void fun1(int *getValue)
{
for(int i=0;i<4;i++)
*getValue++;
}
void fun2(int *getValue)
{
for(int i=0;i<4;i++)
*getValue=+1;
}
void main()
{
int getValue=0,getValu2=0;
fun1(&getValue);
fun2(&getValu2);
printf("getValue :%d and getValu2 : %d\n", getValue, getValu2);
}
Run Code Online (Sandbox Code Playgroud)
以上程序的o/p是
getValue :0 and getValu2 : 1
Run Code Online (Sandbox Code Playgroud)
现在我期待两种情况下的价值应该是4因为我在函数中传递了变量的地址?我的理解是错的,这种行为是否正确?如果是,那么任何人都能解释一下吗?我需要什么修改来获得正确的价值?
#include <stdio.h>
#define CHAR_ROW_SIZE 4
int charTable[CHAR_ROW_SIZE ][2] = {
{'X', 'Z'},
{'J', 'L'},
{'F', 'C'},
{'A', 'B'}
};
int main()
{
printf("char element %c\n", charTable[3][1]); //fine
printf("char element %c\n", charTable[3][8]); // accessing 4th row's 9th element which is not valid
printf("char element %c\n", charTable[85][0]);// accessing 86th row's first element which is not valid
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
char element B
char element
char element
Run Code Online (Sandbox Code Playgroud)
根据我的理解,C\C++ 实际上并没有对数组进行任何边界检查。这取决于操作系统以确保您正在访问有效的内存。所以这是未定义的行为。
但是在这里我可以在不同的机器上看到相同的行为。即程序不会随时崩溃。