Undefined reference error from linker

Hi,
I have to create three projects that share some code and I’d like create this kind of folders structure:
c:\projects\common
|–routines.h
|–routines.cpp
|–<other_common_files>
c:\projects\project1
|–src
|–main.cpp
|–lib
|–<pio_structure>
|-- …
c:\projects\project2
|–src
|–main.cpp
|–lib
|–<pio_structure>
|-- …
c:\projects\project3
|–src
|–main.cpp
|–lib
|–<pio_structure>
|-- …

-platformio.ini code
[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino
build_flags =
-I…/common

-routines.h code
#ifndef routines_h
#define routines_h

extern bool test;
#endif

-routines.cpp code
#ifndef routines_cpp
#define routines_cpp

#include <routines.h>

bool test = true;
#endif

-main.cpp code
#include <Arduino.h>
#include <routines.h>

void setup() {
test = true;
}
void loop() {
}

I’d like all three projects can use routines definited in .h and written in .cpp, but linker give me this error: .pio/build/esp12e/src/main.cpp.o:(.text.setup+0x0): undefined reference to `test’

What’s wrong?
Best regards

  • Why do you have an include-guard in a source-file? You normally only use those in header-files.
#ifndef routines_cpp
#define routines_cpp
...
#endif
  • When using #include using #include <foo.h> is used to include system libraries/header-files while you should use #include "bar.h" to include your own header-files/libraries.

I inserted include-guard block only because of inexperience!
Now I include like you show, but I have same error.
With build_flags = -I…/common pio knows where are my own .h files but not .cpp (same folder).
If I put the .cpp files in the src folder, pio finds them, but I would not put them in src folder, but only in my own “common”, shared for all my projects.
Is there a way to instruct pio to “see” my .cpp files in “common” folder, for example, like a build_flags?

Oh I completely overlooked your project structure. Your “common” folders basically is like your directory of a few custom libraries multiple projects depend on. Therefor you will need to tell your project’s platformio.ini-file where to find those libraries so PIO’s LDF can handle them. Take a look here: Library Dependency Finder (LDF) — PlatformIO latest documentation
So instead of using build flags you probably should use the lib_extra_dirsoption and set that to your common-libraries folder.

1 Like

I read documentations about ldf, I created a new folder called “cpp” with my cpp files under “common”, I added lib_extra_dirs in the platformio.ini with the relative path, but I have the same error

Try with a proper library folder structure… i.e. the lib_extra_dirs would point to the \common folder, which then contains routines, lib2, lib3 etc, which then contain the .h and .cpp for each of the project libraries…

Or I could be completely wrong… I took the cowards way out for ‘common libraries’ and used git submodules! :open_mouth: :laughing: