Включить местную библиотеку
Я пытаюсь скопировать пару библиотек, которые я создал, в свою локальную папку эскизов, как указано в Руководство по библиотеке Arduino
Моя структура папок следующая
Я получаю следующую ошибку
Обратите внимание, что это отлично работает, если я перемещаю свои библиотеки в папку C: \ Program Files (x86) \ Arduino \ libraries , но я действительно не хочу, чтобы они были отделены от моего источника, поскольку я не могу проверить их в моем репозитории git.
Я думаю, что точно следую инструкциям, данным в руководстве. Я просто погуглил об этом и нашел несколько похожих проблем, но без решения. Предполагается, что он работает в последних версиях IDE (я использую 1.8.5 в Windows 10).
Я также попытался включить библиотеки, используя двойные кавычки вместо угловых скобок, но получил ту же ошибку.
Подскажите, пожалуйста, как решить эту проблему?
2 ответа
Последние версии IDE Arduino выполняют рекурсивную компиляцию подпапки src папки эскиза. Итак, для достижения вашей цели вам понадобится структура папок, которая выглядит примерно так:
Тогда директива #include в скетче должна выглядеть так:
Библиотеки Arduino часто используют неправильный синтаксис для своих внутренних директив #include . Например, Timer.cpp может содержать такую строку:
Это не вызывает проблем, если библиотека установлена нормально, но вызовет ошибку, когда вы попытаетесь использовать библиотеку в комплекте с эскизом. Решение — отредактировать библиотеку, чтобы использовать правильный синтаксис:
Мне кажется, что решение выглядит нормально, если библиотеки / Таймер используются только этим скетчем . Что делать, если у вас есть несколько проектов
Если вы хотите избежать дублирования кода (а вы это делаете), вы можете поместить их в
- удалите каталог C: \ Program Files (x86) \ Arduino \ libraries \ Timer
- перезагрузите «.zip» (из
/ libraries / Timer) из Arduino IDE
Что вы можете сделать, так это создать символическую ссылку из
В Ubuntu это будет:
IDE Arduino будет знать, что ваша библиотека существует, и автоматически перекомпилирует ее, если Timer.
Include local library
I’m trying to copy a couple of libraries I created to my local sketch folder, as instructed in the Arduino Library Tutorial
My folder structure is the following
I get the following error
Note that this works just fine if I move my libraries to the C:\Program Files (x86)\Arduino\libraries folder, but I really don’t want to keep them appart from my source since I can not check them to my git repository.
I think I’m following the instructions given in the tutorial precisely. I just googled about this and found several similar problems, but no solution. It’s supposed to be working in recent versions of the IDE (I’m on 1.8.5 on Windows 10).
I also tried to include the libraries using double quotes instead of angle brackets but I got the same error.
Can you please let me know how to fix this problem?
2 Answers 2
Recent versions of the Arduino IDE do recursive compilation of the src subfolder of the sketch folder. So to achieve your goal, you will want a folder structure that looks something like this:
Then the #include directive in the sketch should look like this:
It’s quite common for Arduino libraries to use incorrect syntax for their internal #include directives. For example, Timer.cpp might contain this line:
That doesn’t cause a problem when the library is installed normally but it will cause an error when you try to use the library bundled with a sketch. The solution is to edit the library to use the correct syntax:
It seems to me that the solution looks fine if libraries/Timer is used only by this sketch. What if you have several projects
If you want to avoid code duplication (and you do), then you may put them into
- delete the dir C:\Program Files (x86)\Arduino\libraries\Timer
- reload the «.zip» (from
/libraries/Timer) from the Arduino IDE
What you could do is create a symbolic link from
On Ubuntu that would be :
The Arduino IDE will know your library exists, and would recompile it automatically if Timer.
“.h: No such file or directory” – 2 Easy fixes to Arduino error
Are you trying to run an Arduino sketch, but keep coming across a “No such file or directory” error? This is a pretty common error! Keep watching to learn more about 2 easy fixes for this error.
No such file error!
Error messages can be such a pain, but they’re supposed to tell us something about the error we made. Let’s take a look at the one below. If you look at the bottom portion of the Arduino IDE where the error message shows up, there’s this handy little button that says “copy error messages”.
If you click on it, it copies the error message inside the little window to the clipboard on the computer.
What you can do now is paste it into Google, for example, and do a search which can help you find out more about the error. Or you could paste it into a forum and say, “Hey, I’ve got this error message, please help me.”
For this situation, however, we’ve copied it and we’re going to paste it into a text editor so we can take a closer look at what the error message is actually saying.
Decoding the no such file error
The first sentence just says which Arduino version is in use, which operating system is running, and which board is selected.
The second sentence actually starts getting into the error a little bit. The first thing it gives us is the name of the program. So, in this case, the name of the program was “Knob”.
If you look at the Arduino IDE, the the numbers on the left are called line numbers of the program and they’re a reference to help us find where different lines of code are. The “10” after “Knob” is the line number (in the Arduino IDE) that the error was detected on.
The “19” is a reference to how long that line of code is, so how many spaces or characters long is it.
Then it tells us the actual error. It says “servo.h: No such file or directory”. Why are we getting this error?
The error of our ways
Well, let’s take a look at line 10 and see what it says. It says “#include ”
When we verify this code, what this line does is tell the Arduino IDE compiler “Hey, for this program to work, you need to go get this file servo.h”.
Let’s say you had a label making machine and you were trying to run the label maker and print some labels. To make it work, you have to put in a roll of labels. If you don’t have that roll of labels, then your label maker isn’t gonna work. So our program’s like the label maker and the file (servo) is the roll of labels.
So the error message is like “Hey, programmer, you said I needed this other file… but I looked for it and it’s not there. What gives? Let’s get to the bottom of this error message and go over two different scenarios.
Scenario 1 – fat fingers
This sketch is one that you’ve written. You’re actually the one who wrote the “#include” line. The first thing you should check is your spelling and capitalization. Maybe you spelled the name of the library incorrectly, or in this example, maybe you didn’t capitalize the right letters.
So “servo.h” should actually be a capital “S”, or written out, “Servo.h”. Now in this example, you’ll notice that the word servo changes color when correctly capitalized, and that’s because the library name “Servo” is recognized as a “key word” in the Arduino IDE. Keep in mind that might not be the case for all the libraries that you’re using.
Therefore you can’t use whether or not it color changed as an absolute indicator, but it can be helpful. It is amazing how long you can stare at a line of code and miss something like a spelling or a capitalization error.
Scenario 2 – missing files
In this scenario you’ve either downloaded or copied and pasted some code from the internet and you’re trying to run it for the first time. Now you start getting this error message. Let’s just assume that the original author of the program spelled the name of the library correctly.
We’ll go ahead and skip the troubleshooting associated with scenario 1. The next step would be to verify that we actually have the file this program is calling for. We must also ensure the file is in the correct place.
An easy way to check to see if you have that file is to be in the Arduino IDE and go to Sketch > Include Library, and then look for the name of that library.
Whatever library the #include statement was calling for, you want to look through this big long list for that library. If you don’t see its exact name in this list, this means you do not have that library installed appropriately (they’re all in alphabetical order which helps). If you don’t see it here, you’ll have to add the library.
The easiest way to add a library is to go to Sketch > Include Library > Manage Libraries. It will open up a dialogue box and you can search for a library. There’s so many libraries, you’re definitely going to want to filter.
Make sure you type the exact word that matches the #include line. Once you find the missing library click install. It will let you know that it’s installing the library and updating the list of libraries.
Next we can double-check it has successfully installed. Go to Sketch > Include Library and the installed library should now appear on the drop down list. Now, when it complies, you should no longer get the error.
Other library locations
Not all libraries are in this convenient pop-up window when you go to manage libraries. There’s tons of different ways to find Arduino libraries on the web. Often, if you’re downloading or copying a program from the internet, just go to the page where you got that program and see what library they’re referencing. Maybe they have a link to GitHub, for example, which is a place where people keep a lot of code libraries.
Usually the library is included in a .zip file package. Once you’ve downloaded the .zip file, you can go to the Arduino IDE and go to Sketch > Include Library > Add .ZIP library… You just have to navigate to where the file was downloaded. It will tell you “Library added to your libraries” just above the dark area where the original error had appeared.
Now when we go to Sketch > Include Library, the new library will appear in the drop-down list. Viola! You now know 2 ways to add a new library.
Review
So we’ve discussed two possible scenarios that could cause the “No such file or directory” error to appear after you compile your sketch.
First, if you wrote the sketch, just double-check your spelling and capitalization.
Second, if you have copied code from someone else, make sure you have the correct libraries installed.
We hope you have a great one and we’ll see you next time! Bye!
Включить местную библиотеку
Я пытаюсь скопировать пару библиотек, которые я создал, в свою локальную папку эскизов, как указано в Руководство по библиотеке Arduino.
Моя структура папок следующая
Я получаю следующую ошибку
Обратите внимание, что это отлично работает, если я перемещаю свои библиотеки в папку C: \ Program Files (x86) \ Arduino \ библиотеки, но я действительно не хочу, чтобы они были отделены от моего источника, так как я не могу проверить их в моем репозитории git.
Я думаю, что точно следую инструкциям, данным в руководстве. Я просто погуглил об этом и нашел несколько похожих проблем, но без решения. Предполагается, что он работает в последних версиях IDE (я использую 1.8.5 в Windows 10).
Я также попытался включить библиотеки, используя двойные кавычки вместо угловых скобок, но получил ту же ошибку.
Подскажите, пожалуйста, как решить эту проблему?
Последние версии IDE Arduino выполняют рекурсивную компиляцию подпапки src папки эскиза. Итак, для достижения вашей цели вам понадобится структура папок, которая выглядит примерно так:
Тогда директива #include в скетче должна выглядеть так:
Библиотеки Arduino часто используют неправильный синтаксис для своих внутренних директив #include . Например, Timer.cpp может содержать такую строку:
Это не вызывает проблем, если библиотека установлена в обычном режиме, но вызовет ошибку, когда вы попытаетесь использовать библиотеку в комплекте со скетчем. Решение состоит в том, чтобы отредактировать библиотеку, чтобы использовать правильный синтаксис:
Спасибо! Это сработало просто отлично. Не могли бы вы сообщить мне, если / где это задокументировано?
Как и в случае с некоторыми другими полезными функциями, они никогда не удосужились задокументировать это. Неполная документация особенно досадна в контексте проекта Arduino, который предназначен для начинающих. Сколько новичков будут копаться в исходном коде arduino-builder в поисках недокументированных функций? Я понимаю, что программисты любят писать код, а не документацию, но разве мы не достаточно взрослые, чтобы выполнять важные части нашей работы, даже если они нам не нравятся? Какой смысл добавлять функцию, о которой никто не знает?
Много обсуждений, охватывающих некоторые из основных причин здесь github.com/arduino/Arduino/issues/5186, если кому-то нужны дальнейшие идеи
Мне кажется, что решение выглядит нормально, если для библиотек / таймера стоит используется только в этом скетче. Что делать, если у вас есть несколько проектов
Если вы хотите избежать дублирования кода (а вы это делаете), вы можете поместить их в
- удалите каталог C: \ Program Files (x86) \ Arduino \ libraries \ Timer
- перезагрузите «.zip» (из
/ libraries / Timer) из Arduino IDE
Что вы можете сделать, так это создать символическую ссылку из
В Ubuntu это будет:
IDE Arduino будет знать, что ваша библиотека существует, и автоматически перекомпилирует ее, если Timer.