Built in types become unavailable when I move code to cpp file

I am experiencing some weirdness… I have 2 files foo.ino and bar.h using the Particle Dev IDE. Everything compiles fine until I move the implementation of one of my private methods from the .h file to a newly created .cpp file. The first error is ‘uint16_t has not been declared’ - which happens to be one of the args to my constructor in the .h file. There’s a long list of errors where I’m using other standard types also, the uint16_t just happens to be the first.

foo.ino

#include "bar.h"

Bar bar((const char[]){ 10, 1, 1, 1 }, 8080);

void setup() { }
void loop() { bar.doStuff(); }

bar.h

#ifndef _bar_
#define _bar_

class Bar
{
public:
    Bar(const char * host, uint16_t port) : host(host), port(port) { }
    void doStuff() { baz(); }
private:
    bool baz();

    const char * host;
    uint16_t port;
};

#endif

bar.cpp

#include "bar.h"

bool Bar::baz()
{
    return true;
}

As I mentioned, if I delete the cpp file and move the implementation of baz() to bar.h, everything works fine. Also, if I add #include <stdint.h> to the top of bar.h it compiles with the cpp file. While I can obviously work around this, I wouldn’t mind knowing:

  • why this is happening (or is it just me being pedantic)
  • am I doing something less than ideal by adding the stdint include to work around the problem
  • what should I be doing different, if anything

Oh yeah, and adding #pragma SPARK_NO_PREPROCESSOR to the top of my ino file doesn’t change anything, if that helps.

Many thanks

#include "Particle.h"

Try that

3 Likes

Works, as does adding the stdint include, but doesn’t really answer my question. I’m more concerned with why success turns to failure when the implementation is moved to a cpp file.

When you have a .ino file the Arduino preprocessor is enabled. This includes the default header files (Particle.h/application.h) and also creates forward declarations for functions implemented after they’re used.

When you use a .cpp file extension, you’re using a plain gcc C++ compiler, which does not have built-in header files, so you should

#include "Particle.h"

Ok… I’m still using the .ino file just so we’re clear. The issue arises simply by adding a .cpp file to the project.

No, the “issue” is that you moved your code from a .h file that was included after the implicitly added #include "Particle.h" which also makes the the definitions available to a .cpp file where these definitions don’t apply since .cpp files are not included into the main file but get compiled as seperate module.

1 Like

Ah I see. Thanks for the explanation.