Compiling error on simple Serial.begin() call

I'm having trouble in calling a very typical function on a included file at setup() in a single include (.h) file. Here is the extremely simple code:

serial_com.h file:

#pragma once

void setupSerial(int baud_rate);

serial_com.cpp file:

#include "serial_com.h"

void setupSerial(int baud_rate)
{
    Serial.begin(baud_rate);
    while (!Serial);

    Serial.print("Serial com connected at: ");
    Serial.println(baud_rate);
}

serial_setup.ino file:

#include "serial_com.h"

void setup()
{
    setupSerial(9600);
}

void loop()
{
    // Do nothing
}

This is pretty basic, right? And yet the compiler gives me the following error:

Arduino: 1.8.19 (Linux), Board: "Arduino Uno"

sketch/serial_com.cpp: In function ‘void setupSerial(int)’:
serial_com.cpp:5:5: error: ‘Serial’ was not declared in this scope
     Serial.begin(baud_rate);
     ^
exit status 1
‘Serial’ was not declared in this scope

Can you help me with what's going on? The function Serial.begin(baud_rate) is clearly an included one, is part of the core Arduino, so, how it can't find it? I need this specific kind of arrangement for my projects and if Arduino can't work this way it will make impossible my projects altogether!

serial_com.cpp is compiled separately from your .ino file, so it doesn't get the benefit of all the automagically included Arduino stuff.

Try adding #include <Arduino.h> to the top of the .cpp file.

I included the Arduino.h on the header file and now compiles, like so:

#pragma once
#include <Arduino.h>

void setupSerial(int baud_rate);

Nevertheless the compiler returned the first line as a red line, this is the output:

Archiving built core (caching) in: /tmp/arduino_cache_228867/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a
Sketch uses 1442 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 184 bytes (8%) of dynamic memory, leaving 1864 bytes for local variables. Maximum is 2048 bytes.

So, I'm still doubtful this was the real solution...

Please forget I said anything then. Sheesh.

I was writing this reply before seeing anything else, that's why. But after reading your reply I now know indeed this is the solution.

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