Why do we need the 'extern' keyword in C if file scope declarations have external linkage by default?

前端 未结 4 792
不思量自难忘°
不思量自难忘° 2020-12-14 20:34

AFAIK, any declaration of a variable or a function in file scope has external linkage by default. static mean \"it has internal linkage\",

4条回答
  •  误落风尘
    2020-12-14 20:54

    You can only define a variable once.

    If multiple files use the same variable then the variable must be redundantly declared in each file. If you do a simple "int foo;" you'll get a duplicate definition error. Use "extern" to avoid a duplicate definition error. Extern is like saying to the compiler "hey, this variable exists but don't create it. it's defined somewhere else".

    The build process in C is not "smart". It won't search through all the files to see if a variable exists. You must explicitly say that the variable exists in the current file, but at the same time avoid creating it twice.

    Even in the same file, the build process is not very smart. It goes top to bottom and it won't recognize a function name if it is defined below the point of use, so you must declare it higher up.

提交回复
热议问题