Return doesn't work with a String function ?!

Hello !

I’ve just began writing some code and I stumbled upon a scope error.
The thing is that the same code compiles without errors or warnings in Arduino IDE.

The following code is a simplified version of my own code; it’s just a means of emulating the error:

main.cpp

#include <Arduino.h>

void makeLog() {
  String string = logPath(); // error: `logPath` was not declared in this scope
}

String logPath() {
  String currentPath = "";
  currentPath = "/logFile.txt";
  return currentPath;
}

void setup() {
  // put your setup code here, to run once:

}

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

}

When attempting to build it, I have the following output:

src/main.cpp: In function 'void makeLog()':
src/main.cpp:5:27: error: 'logPath' was not declared in this scope
String string = logPath(); // error: `logPath` was not declared in this scope
^
*** [.pioenvs/esp32doit-devkit-v1/src/main.cpp.o] Error 1

platformio.ini

[env:esp32doit-devkit-v1]
platform = https://github.com/platformio/platform-espressif32.git#feature/stage
board = esp32dev
framework = arduino
board_build.flash_mode = qio
upload_port = /dev/ttyUSB0
monitor_port = /dev/ttyUSB0
monitor_speed = 115200

#libraries
#lib_deps = ESP Async WebServer

Place String logPath(); at beneath #include <Arduino.h> to declare its prototype before hand. This is C++ error. The function you are calling must be declared at the point of the call. This only works in the Arduino IDE because it auto-generates the prototypes for you, but it’s not valid C/C++ per-se.

See Redirecting...

2 Likes

Thank your for your reply !

That was, indeed, the issue !

The other way to do it is to place the whole

String logPath() {
  String currentPath = "";
  currentPath = "/logFile.txt";
  return currentPath;
}

above the first function that accesses it, makeLog() in this instance, and then you don’t need to put in the function prototype, but really isn’t good practise, as it would mean you would have to reshuffle the function definitions around if the order of them being accessed changed. But this is why you may see some code written without function prototypes/declarations.

1 Like

Thank you for your reply !

This is what I’ve actually ended up using.

If function x needs function y, then I would’ve defined function y before function x.

But from now on I will start declaring the functions at the beginning of the code and then define them.

1 Like