Reputation: 21
I'm using VS Code with an Arduino Mega and I'm trying to figure out the best way to implement a multi-file workflow. So far I have been able to incorporate a header file, however I'm not sure how to get the extension to include the other .cpp files into the build.
Current folder structure:
-Workspace
---main
-----main.ino
---src
-----add.cpp
-----add.h
So it builds main.ino fine, and includes the header fine, but of course it's not compiling add.cpp. This isn't unexpected, as I haven't told the compiler to include it. For g++ compiling I've always just included the .cpp files as arguments, i.e. "${fileDirname}\*.cpp", in the tasks.json. I can't find any good instructions for how to do similar using the Arduino for VS Code extension. What is the best way to have VS Code build all relevant .cpp files for Arduino?
Thanks!
Upvotes: 0
Views: 3308
Reputation: 1
I have found a temporary solution to this problem, do not now if it is a good one, in terms of the professional coding guidelines.
Say, we have the following structure:
-Workspace
---main
-----main.ino
---src
-----add.cpp
-----add.h
then in main:
#include <Wire.h>
#include "src/add.h"
void setup(){
your code here
}
contine the code.
then in add.h:
#ifndef _ADD_H_
#define _ADD_H_
Your code
#include "add.cpp"
#endif
and in add.cpp:
#include "add.h"
your code comes here
Then the source code for the library add should also get compiled. I struggled with a simmilar problem, and found this thread. This solution I am proposing works for me, without the use of platform.io (which was not an option for me). But like I said, I do not know if this is according to some professional coding guidelines.
Upvotes: 0
Reputation: 17
The cpp file should habe been compiled but linked if needed. You dont need to tell the compiler to compile that file. Just include the header file in both files: main.cpp and add.cpp.
Your header file must look similar to this
#ifndef ADD_H__
#define ADD_H__
//All your code
#endif //ADD_H__
This precompiler trick will allow you to include your header anywhere but will prevent the redefinitions.
Upvotes: 0
Reputation: 1069
Plain and simple by using the free platformio plugin for vs code. The best solution I found for working with arduino.
This plugin is reliable, platform independent, open source and you can manage projects with header files and the linking and compiling is done by dialogue. Also the documentation is well written.
I hope you have as much fun programming with it as I do :)
Upvotes: 1