Using extern keyword to call functions

旧巷老猫 提交于 2019-12-02 02:26:55

问题


I want to call functions defined in test.c from other.c.

Can I extern the function1 to call it? Also, do I have to use extern in function2 and function3, which are being called by function1?

other.c

extern function1();
function1();

test.c

void function1()
{
    function2();
    function3();
}

void function2()
{

}

void function3()
{

}

回答1:


Function declarations are "by-default" extern.

Quoting C11, chapter §6.2.2, (emphasis mine)

If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. [...]

So, you don't need to be explicit about it.

You need to compile the translation units aka source files (into object files) and then link them together to build the executable. That should do it.




回答2:


extern simply tells us that it is defined somewhere else. And you are using it in the file you are writing the extern. But functions are by default extern. So you need not be explicit about it.




回答3:


Actually every function by default is extern :) - unless you declare them to be not :). It is enough if you have the prototype before the first call;

int xxx(int, int, float, double);  // prototype


int main(void)
{
  int x,y;
  float z;
  double v;

  xxx(x,y,z,v);

  return 0;
}

Function can be in the another .c file. You need to include the object file to the linking.

int xxx(int a, int b, float c, double d)
{
  int result;
  /* do something */

  return result;
}



回答4:


You use extern to declare symbols which are external to the current translation unit (roughly a single source file with all its included header files).

Simple example

The first source file test1.c

extern void function1(void);  // "Import" a function from another translation unit

int main(void)
{
    function1();  // Can call the declared function
}

Then the second source file test2.c:

void function2(void)
{
    // Do something
}

void function1(void)
{
    function2();  // No extern needed, it's declared (and defined)
                  // in the same translation unit
}

As you can see the function function2 doesn't need any extern declaration anywhere. It is used only in test2.c so only function1 needs to know about it.

However in test1.c the main function needs to know about function1 because it is called, then we make a forward declaration of the function prototype. This is done using the extern keyword. But for declaring functions the extern keyword isn't actually needed, as they are always considered "external" (as noted by Peter).



来源:https://stackoverflow.com/questions/45923026/using-extern-keyword-to-call-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!