When is it necessary to use "extern"

Most of my programs in which I have routines outside the LOOP brackets ( loop{} ) work fine. For example this construct works just

void loop {
int a = 1;
int b = 2;
int c = addem( a, b );

int addem(int a, int b)
ret a + b;

When compiling, some programs report that the function “addem()” was not declared. Others don’t seem to care and compile successfully.
When I encounter this issue, I resolve it by adding an “extern” definition “extern int addem(int a, int b)”. Under what conditions do I need to add an “extern” declaration?

Post the program that doesn’t work, not the one that does.

The Arduino system tries to add “prototypes”, also known as “forward declarations” to the top of your sketch so all of the functions are declared at the top. That way they (try to) save you from get a “not defined in this scope” error when you put the definition of a function BELOW where the function is used.

There are ways the automatic prototype can fail. When they do, you get the “not defined in this scope” error. You can fix that by putting in a prototype yourself. That’s what you did… the ‘extern’ keyword is not needed.

The ‘extern’ is needed when you are using a function or global variable that is defined in a different file. It tells the compiler that the linker will find the address of the function or variable among the various files included in the link. Those are typically files from the Arduino core or libraries. The linker will give an error if the ‘extern’ variable is never defined (or defined more than once).

1 Like

Thanks for your response. Got the answer I needed…

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.