Using extern keyword to call functions

2019-02-26 13:16发布

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()
{

}

4条回答
我命由我不由天
2楼-- · 2019-02-26 13:40

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;
}
查看更多
ら.Afraid
3楼-- · 2019-02-26 13:45

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.

查看更多
迷人小祖宗
4楼-- · 2019-02-26 13:50

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).

查看更多
等我变得足够好
5楼-- · 2019-02-26 14:06

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.

查看更多
登录 后发表回答