undefined reference error in library

I can’t find my error in the following syntax, when creating a library:

sketch.ino:

#include <mylib.h>

void setup() {
  // put your setup code here, to run once:
mylib.test();
}

void loop() {
  // put your main code here, to run repeatedly:

}

libraries/mylib/mylib.h:

#ifndef MYLIB
#define MYLIB

class myLib {

 public:
  bool test();

 private:
  int testVar;

};

extern myLib mylib;

#endif

libraries/mylib/mylib.cpp:

#include <mylib.h>

bool myLib::test(){
	testVar = 69;
	return true;
}

I get the compiler error:

C:\tmp\Arduino\libraries\mylib/mylib.cpp:4: undefined reference to `mylib'

C:\tmp\Arduino\libraries\mylib/mylib.cpp:4: undefined reference to `mylib'

collect2.exe: error: ld returned 1 exit status

Using library mylib in folder: C:\tmp\Arduino\libraries\mylib (legacy)
exit status 1
Error compiling for board Arduino Pro or Pro Mini.

What am I missing?

You didn't define the mylib variable in your .CPP file:

myLib mylib;

The line with "extern" in your header file is just a declaration, not a definition.

Pieter

Thanks!

If I don't use variables, that are declared in the class, then the code compiles fine. Why?

I'm not sure what you mean. If you don't use the "mylib" variable, it doesn't matter if it's defined or not.

I mean if I don't use "testVar" (or declare it right inside the function), then it compiles just fine.

Please post the code instead of describing it.
“testVar” is not an extern global variable.

The sketch is unchanged.

mylib.h

#ifndef MYLIB
#define MYLIB

class myLib {
 public:
  bool test();
};

extern myLib mylib;

#endif

mylib.cpp

#include <mylib.h>

bool myLib::test(){
	int testVar = 69;
	return true;
}

This compiles fine, but if I declare any variable in the header file, that I want to use inside the library, I get the undefined reference error. Just trying to understand…

As noted, this:

extern myLib mylib;

only declares a variable of type myLib named mylib (BTW that's a very bad idea to make the variable name so close to the type name).

But, it does not define that variable. See:
https://www.cprogramming.com/declare_vs_define.html
https://www.tutorialspoint.com/What-is-the-difference-between-a-definition-and-a-declaration-in-Cplusplus