STM32

c언어 extern

풀등 2022. 12. 17. 13:29

In C programming,

the extern keyword is used to declare a variable or function that is defined in another source file.

It can be used to make a variable or function available to multiple source files in a program.

Here is an example of using the extern keyword in C:

 

File 1 (main.c):

#include <stdio.h>

// Declare a global variable extern int x;
extern int x;

int main()
{
    // Access the value of x
    printf("x = %d\n", x);
    return 0;
}

 

 

File 2 (extern.c):

// Define the global variable x
int x = 10;

 

 

To use the extern keyword,

you must first declare a variable or function in one source file using the extern keyword, and then define it in another source file.

In the example above, the variable x is declared as extern in main.c,

and then defined with a value of 10 in extern.c. When main.c is compiled and linked with extern.c, the value of x can be accessed and used in main.c.

Note that the extern keyword is only used for declarations, not definitions.

To define a variable or function, you must provide a type and a name, but you do not use the extern keyword.

You can also use the extern keyword to access variables and functions defined in other libraries or external object files. For example:

 

#include <stdio.h>

// Declare a function extern int add(int a, int b);
extern int add(int a, int b);

int main()
{
    // Call the add function
    printf("The sum is %d\n", add(2, 3));
    return 0;
}

 

 

In this example, the function add is declared with the extern keyword in main.c,

and then defined in another source file or library.

When main.c is compiled and linked, the add function can be called and used in main.c.