Содержание
- Common C++ Error Messages #1 – No such file or directory
- Arduino.ru
- Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
- forum.arduino.ru
- Ошибка при компилировании.
- “.h: No such file or directory” – 2 Easy fixes to Arduino error
- No such file error!
- Decoding the no such file error
- The error of our ways
- Scenario 1 – Fat fingers
- Scenario 2 – Missing files
- Other library locations
- Review
- Michael James
- The Programming Electronics Academy
- Are you ready to use Arduino from the ground up?
- 24 Comments
Common C++ Error Messages #1 – No such file or directory
Introduction
In this intermittent series, I’ll be looking at the most common error messages your C++ compiler (and linker) can produce, explaining exactly what they mean, and showing how they can be fixed (or, better still avoided). The article will specifically talk about the errors produced by the GCC command line compiler, but I’ll occasionally provide some coverage of Microsoft C++ as well. The articles are aimed at beginner to intermediate C++ programmers, and will mostly not be OS-specific.
Error Messages 101
Compiler error messages from the GCC g++ compiler generally look like something this:
which was produced by this code:
The first line of the error says which function the following error(s) is in. The error message itself comes in four main parts; the file the error occurs in, the line number and character offset at which the compiler thinks the error occurs, the fact that it is an error, and not a warning, and the text of the message.
As well as error, the compiler can also produce warnings. These are usually about constructs that, while not being actually illegal in C++, are considered dubious, or constructs that the compiler has extensions to cover. In almost all cases, you don’t want to use such constructs, and you should treat warnings as errors; in other words, your code should always compile with zero warnings. You should also increase the level of warnings from the compiler’s default, which is usually too low. With g++, you should use at least the -Wall and -Wextra compiler options to do this:
No such file or directory
The error I’m looking at today most commonly occurs when you are including a header file using the preprocessor #include directive. For example, suppose you have the following code in a file called myfile.cpp:
and you get the following error message:
What could be causing it? Well, the basic cause is that the compiler cannot find a file called myheader.h in the directories it searches when processing the #include directive. This could be so for a number of reasons.
The simplest reason is that you want the compiler to look for myheader.h in the same directory as the myfile.cpp source file, but it can’t find it. this may be because you simply haven’t created the header file yet, but the more common reason is that you either misspelled the header file name in the #include directive, or that you made a mistake in naming the header file when you created it with your editor. Look very closely at the names in both the C++ source and in your source code directory listing. You may be tempted to think «I know that file is there!», but if the compiler says it isn’t there, then it isn’t, no matter how sure you are that it is.
This problem is somewhat greater on Unix-like system, such as Linux, as there file names are character case sensitive, so Myheader.h, MyHeader.h, myheader.h and so on would all name different files, and if you get the case wrong, the compiler will not look for something «similar». For this reason, a very good rule of thumb is:
Never use mixed case when naming C++ source and header files. Use only alphanumeric characters and the underscore when naming C+++ files. Never include spaces or other special characters in file names.
Apart from avoiding file not found errors, this will also make life much easier if you are porting your code to other operating systems which may or may not respect character case.
The wrong directory?
Another situation where you may get this error message is if you have split your header files up from your C++ source files into separate directories. This is generally good practice, but can cause problems. Suppose your C++ project is rooted at C:/myprojects/aproject, and that in the aproject directory you have two sub-directorys called src (for the .cpp files) and inc (for the header files), and you put myfile.cpp in the src directory, and myheader.h in the inc directory, so that you have this setup:
Now if you compile the source myfile.cpp from the src directory, you will get the «No such file or directory» error message. The C++ compiler knows nothing about the directory structures of your project, and won’t look in the inc directory for the header. You need to tell it to look there somehow.
One thing some people try when faced with this problem is to re-write myfile.cpp so it looks like this:
or the slightly more sophisticated:
Both of these are a bad idea, as they tie your C++ code to the project’s directory structure and/or location, both of which you will probably want to change at some point in the future. If the directory structure does change, you will have to edit all your #include directories.The better way to deal with this problem is to tell the compiler directly where to look for header files. You can do that with the compiler’s -I option, which tells the compiler to look in the specified directory, as well as the ones it normally searches:
Now the original #include directive:
will work, and if your directory structure changes you need only modify the compiler command line. Of course, writing such command lines is error prone, and you should put such stuff in a makefile, the use of which is unfortunately outside the scope of this article.
Problems with libraries
Somewhat similar issues to those described above can occur when you want to use a third-party library. Suppose you want to use the excellent random number generating facilities of the Boost library. If you are copying example code, you may well end up with something like this in your C++ source file:
This will in all probability lead to yet another «No such file or directory» message, as once again the compiler does not know where «boost/random.hpp» is supposed to be. In fact, it is one of the subdirectories of the Boost installation, and on my system I can get the #include directive to work using this command line:
where /prog/boost1461 is the root directory for my specific Boost library installation.
Can’t find C++ Standard Library files?
One last problem that beginners run into is the inability of the compiler to find header files that are part of the C++ Standard Library. One particular favourite is this one:
where you are learning C++ from a very, very old book. Modern C++ implementations have not contained a file called iostream.h for a very long time indeed, and your compiler is never going to find it. You need to use the correct, standard names for such headers (and to get a better book!):
If this still fails, then there is almost certainly something very wrong with your GCC installation. The GCC compiler looks for Standard Library files in a subdirectory of its installation, and locates that directory relative to the directory containing the compiler executable, so if the Standard Library headers are available, the compiler should always find them.
Conclusion
This article looked at the «No such file or directory» message of the GCC C++ compiler. If you get this message you should:
- Remember that the compiler is always right in situations like this.
- Look very closely at the file name to make sure it is correct.
- Avoid naming file using mixed-case or special characters.
- Use the -I compiler option to tell the compiler where to look for files.
- Make sure that GCC is correctly installed on your system.
Источник
Arduino.ru
Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
forum.arduino.ru
Ошибка при компилировании.
При компилировании выдает такое сообщение:
fatal error: ../Wire/Wire.h: No such file or directory
Библиотеки все установлены. Если вы это имеете ввиду. Проверял. Эта ошибка произошла после перехода на версию IDE 1.8. По крайней мере так совпало. Пробовал компилировать под 1.6.10. которая была раньше. Пишет:
Arduino: 1.6.10 Hourly Build 2016/06/06 08:34 (Windows 7), Плата:»Arduino/Genuino Uno»
refrigerator_temp_frozen:51: error: ‘lcd’ does not name a type
но не находит, сделайте, чтобы находил, тема всплывала, поройтесь поиском
При этом скетч работал нормально с подключеным LCD дисплеем. Пробовал другие скетчи с дисплеем, тоже не работают.
Дисплей тут вообще не при чём, среда тупо не может найти заголовочный файл.
Замените #include на #include
Библиотеки все установлены.
Установлены, но путь указан неверно. По крайней мере в Arduino IDE 1.6.13 этот файл находится тут: WiresrcWire.h
Установил 1.6.13. Проверил, файл Wire.h находится C:UsersАндрейYandexDiskArduino1.6.13hardwarearduinoavrlibrariesWiresrcWire.h
Все равно не компилируется.
В сообщении об ошибке есть строка C:UsersАндрейDocumentsArduinolibrariesLiquidCrystalsrcI2CIO.cpp:35:26: fatal error: ../Wire/Wire.h: Мне почему-то кажется что библиотека LiquidCrystal пытается найти этот файл по адресу /Wire/Wire.h и не находит.
avgustdon, ошибка может быть в том, что у вас в пути к ардуино есть папки, названные кириллицей («Андрей»). Много раз встречал в сети сообщения, что Ардуино IDE этого не любит. Переинсталлируйте Ардуино, скажем, в папку D:Arduino
ЗЫ Не только для ардуино, а вообще. не стоит называть папки кириллицей . Очень многие программы глючат от этого.
avgustdon, ошибка может быть в том, что у вас в пути к ардуино есть папки, названные кириллицей («Андрей»). Много раз встречал в сети сообщения, что Ардуино IDE этого не любит. Переинсталлируйте Ардуино, скажем, в папку D:Arduino
ЗЫ Не только для ардуино, а вообще. не стоит называть папки кириллицей . Очень многие программы глючат от этого.
Не помогло. Я этот вариант в самых первых попытках пробовал. Сейчас еще попробовал. Тот же результат.
Источник
“.h: No such file or directory” – 2 Easy fixes to Arduino error
It’s 11 PM on a Wednesday. You’ve just spent three hours toiling on your next Arduino project, and FINALLY, you’re ready to give your sketch a whirl. You hit upload, palms sweaty with anticipation to see all your hard work come to fruition. It’s then you see the error:
No such file or directory.
Surely this is a chance aberration. “Nothing to worry about,” you mutter, sleep-starved and semi-delirious as you hit upload again. And once more, those maddening words, “no such file or directory,” stare back at you in hostile gaslighting mockery.
Have you been here?
If you’re trying to run an Arduino sketch but keep coming across the “no such file or directory” error, don’t worry. This is actually a pretty common problem, and there are two easy fixes that almost always work.
Keep on reading. We’ll show you what they are.
No such file error!
Error messages can be such a pain. They do, however, serve a useful purpose by telling us something about what went wrong. At first glance, the no such file or directory error is particularly maddening because it seems to break that useful purpose rule. Of course there’s a file or directory! You just made the thing, and it’s right there, tucked inside a directory.
But hold up, let’s take a closer look. 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.”
Click on that now. You probably won’t fall off your chair to learn that by clicking that button, you just copied the error message from the little window at the bottom of The Serial Monitor’s UI to the clipboard of your computer.
This copy feature is ridiculously useful. You could, for example, paste the error message into Google and learn more about the error. Or you could take advantage of the active Arduino community by asking for help in a forum. For this situation, however, we can be a bit more basic. All we’re going to do is take a closer look at what the message is actually saying. To do that, just fire up your PC’s text editor and paste it into the blank screen.
Decoding the no such file error
Here it is, that pesky error in all its freshly pasted glory.
I’ll break it down for you line by line.
- The first line is easy. It’s just describing the Arduino version in use, what operating system is running, and which board you have selected.
- Line 2 begins to zero in on the problem.
- The first bit, “knob,” is referring to the name of the program. This is your sketch, basically.
- The second bit is what usually begins to confuse people, but it’s easy once you know. The “10” in this example is telling you the error occurred on line 10 of your sketch. The “19” is telling you the length of the line of code in spaces and characters. The first number is usually the more helpful of the two because you can use it to locate the error in your sketch.
- Then we get to the smoking gun of the error. It says, “servo.h: No such file or directory”.
So this thing, “Servo.h.” That’s the thing we need to fix, and thanks to line 2, we know where to find it. Line 10. It’s always line 10.
Now that we know what’s going on a bit better, let’s get down to the business of implementing a fix.
The error of our ways
Let’s lay down some scrutiny on this accursed line 10.
It says “#include ”
When we verify this code, this line is telling the Arduino IDE compiler, “Hey, for this program to work, you need to go get this file called servo.h”.
Let’s say you had a label-making machine, and you wanted to use it to print some cool motivational labels, like “Success!” and “Keep Trying!” and “Look, Nachos!” To make that happen, you’ll first have to load in a roll of labels. No roll of labels? Well, then the label maker isn’t gonna work.
The sketch you’re trying to upload is like the label maker. The file (in our example, the file named “servo.h”) is the roll of labels.
So the error message actually is saying something useful. It’s saying, “Hey programmer, you said I needed this other file. Well, I looked for it and it’s not there. What gives?”
Now we know the error message isn’t complete gibberish, let’s look at the two most common scenarios that cause it.
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 (as with the example below) perhaps you capitalized the wrong letters.
So “servo.h” should actually have a capital “S.” In full and with correct capitalization, it should read, “Servo.h.” You’ll notice above that the word servo changes color when it’s correctly capitalized. That color change signifies that the library name “Servo” is recognized as a “keyword” in the Arduino IDE.
Keep in mind that might not be the case for all the libraries you’re using. In other words, the color change won’t always indicate you’re using the right spelling or capitalization, but it’s often a helpful visual reminder.
Oh, and it’s probably good to mention that everyone in the history of Arduino programming has misspelled or incorrectly capitalized a word at some point. It’s amazing how long you can stare at a line of code and miss something like that.
So don’t sweat it.
Scenario 2 – Missing files
This brings us to the next common scenario for the “no such file or directory” error.
So often, working with Arduinos involves taking code that someone else has developed and shared online and then tailoring it to your project. That’s part of what makes it so easy to get stuff done with Arduino. One problem that frequently happens when we do that, however, is we accidentally introduce code without a matching file.
An easy way to check to see if you have the file a sketch is looking for is to navigate to Sketch > Include Library from within the Arduino IDE. 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 a library with the exact same name. If you don’t see the file name there, this means the library isn’t installed. You’ll have to add that library before the sketch will compile without errors.
So, how do you add that library?
The easiest way is to go to Sketch > Include Library > Manage Libraries. The Arduino IDE will open up a dialogue box from which you can search for the library you need.
Make sure you type the exact word that matches the #include line. Once you find the missing library, go ahead and click Install. The Arduino IDE will let you know that it’s installing the library you requested and updating the software accordingly.
Next, just double-check that the library has been successfully installed by going to Sketch > Include Library. You should see your new library in the dropdown list.
Good news! If the library is there, you should now be able to compile your sketch error-free.
Other library locations
OK, there’s one little fly in the ointment. How do these dang ointment flies always manage to complicate things so?
Here’s the thing. Not all libraries live in this convenient pop-up window inside the Arduino IDE. The Arduino community is bubbling with clever ideas, but cleverness (unlike processed cheese) doesn’t always come in conveniently standardized, individually wrapped slices. There are tons of different ways to find Arduino libraries on the web.
If you’re downloading or copying a program from the internet, just go to the page where you got that program and take a close look at the library the author is referencing. They may, for example, have a link to GitHub, which is a place where people keep a lot of code libraries.
Wherever you find it, usually the library will be included in a .zip file package. Once you’ve downloaded the .zip file, fire up the Arduino IDE and go to Sketch > Include Library > Add .ZIP library. Then navigate to the location you downloaded the file and select it. Assuming no additional ointment flies invade your workflow, the Arduino IDE will pop up the message “Library added to your libraries” just above the dark area where the original “no such file or directory” error appeared.
Now it’s business as usual! Just go to Sketch > Include Library, and the new library will appear in the drop-down list.
As the dyslexic Frenchman once said to the oversized violinist: “Viola!”
You now know not one but two ways to add a new library. What a time to be alive!
Review
A quick recap, then.
We’ve looked at the two main scenarios that cause the “no such file or directory” error to appear after you compile your sketch:
- The fat fingers phenomenon: Check your spelling and capitalization! If you wrote the sketch, there’s a mighty good chance you introduced a tiny error. And don’t beat yourself up over it! Literally every coder has done this.
- The missing files mixup: Failing that, if you copied code from someone else check that you have the correct libraries installed. Don’t see your library? Install it using the method described above, and you should be good to go.
There may be no such thing as a free lunch, a coincidence, or a luck dragon. But rest assured. Your files and directories? They’re alive and well.
Michael James
Proud Member of
The Programming Electronics Academy
The place where we help you get started and scale the mountain of knowledge of the Arduino Platform. That means we teach what is practical , what is useful , and what will get you off to a running start.
Learn more About Us Here
Are you ready to use Arduino from the ground up?
(without spending days going down YouTube rabbit holes)
- Learn the 2 most important Arduino programming functions
- Get familiar with Arduino coding
- Understand your Arduino hardware
- Learn the Arduino software setup
- 12 engaging video lessons
Should you decide to sign up, you’ll receive value packed training emails and special offers.
Wait for it. we’ll be redirecting you to our Training Portal
Great video showing how to include libraries and search libraries if you don’t see a library in your sketch book.
Please keep up the great work. Making Arduino code writing easier.
Thanks,
Jack Brockhurst
Thanks Jack! We’ll do our best to keep them coming.
Great tips! thanks for the tutorials.
Thanks Daniel! I am glad it was helpful.
Tutorials are very comprehensive! Thanks!!
Thank you Juven! I am glad they helped!
Very clear and helpfull
Thanks ! !
Hi, I have the same problem: no such file or directory when trying to run ‘Keypad’, so I noticed it wasn’t written in orange.
I see that I didn’t have it in my library (closest thing was Keyboard) so I went to the library manager and downloaded it.
This time it’s in orange, ran the code again, same message. (. )
Tried to put the code in by clicking on it from the Sketch –> Include etc, and a weird thing happens: first row: #include written in black, and second row: #include written in orange.
I’m trying to use it for a 4×4 keypad
Same. Did you find the fix already?
// reset ESP8266 WiFi connection AT+CIPMUX=1 AT+CWJAP
String cmd=”AT+CWJAP=”, EngineersGarage “,”01234567672″”;
lcd.print(” SENDING DATA”);
lcd.print(” TO CLOUD”);
// TCP connection AT+CIPSTART=4,”TCP”,”184.106.153.149″,80
String cmd = “AT+CIPSTART=4,”TCP”,””;
cmd += “184.106.153.149”; // api.thingspeak.com
String getStr = “GET /update?api_key=”;
// send data length
// thingspeak needs 15 sec delay between updates
in this program i got an error expected initializer before string constant
Liquid crystal _I2C.h :No such file or directory
Did all thibg but it is not happening
Arduino: 1.8.15 (Mac OS X), Board: “Arduino Uno”
Multiple libraries were found for “Usb.h”
checkm8-a5:4:10: fatal error: Constants.h: No such file or directory
Used: /Users/sana/Documents/Arduino/libraries/USB_Host_Shield_2.0
#include “Constants.h”
^
compilation terminated.
Not used: /Users/sana/Documents/Arduino/libraries/USB_Host_Shield_Library_2.0
Not used: /Users/sana/Documents/Arduino/libraries/USBHost
exit status 1
Constants.h: No such file or directory
This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.
Looks like you may not have your Constants.h file in your sketch folder?
j’ai suivi la démarche a la lettre mais je ne suis pas arrivé
a trouver la bibliothèque RFID.
avez vous une idée ou je peux la trouver
merci
I followed the process to the letter but I did not arrive
find the RFID library.
do you have an idea where i can find it
thank you
Is there a specific RFID library you are working with? Do you have a link to its GitHub repo by chance?
I am having trouble with the Radiohead RFM95 encrypted client example, seems Speck.h shows as no such file or directory. I can find code for Speck.h but not as a file I can drop in my library. I imagine there is a way to create the right file type in VS but I am not familiar with how to do that, assuming that would even do the trick. I would appreciate a little help here as I am rather new to Arduino and C++.
Here is the sample library:
// LoRa Simple Hello World Client with encrypted communications
// In order for this to compile you MUST uncomment the #define RH_ENABLE_ENCRYPTION_MODULE line
// at the bottom of RadioHead.h, AND you MUST have installed the Crypto directory from arduinolibs:
// http://rweather.github.io/arduinolibs/index.html
// Philippe.Rochat’at’gmail.com
// 06.07.2017
#include
#include
#include
RH_RF95 rf95; // Instanciate a LoRa driver
Speck myCipher; // Instanciate a Speck block ciphering
RHEncryptedDriver myDriver(rf95, myCipher); // Instantiate the driver with those two
float frequency = 868.0; // Change the frequency here.
unsigned char encryptkey[16] = <1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16>; // The very secret key
char HWMessage[] = “Hello World ! I’m happy if you can read me”;
uint8_t HWMessageLen;
void setup()
<
HWMessageLen = strlen(HWMessage);
Serial.begin(9600);
while (!Serial) ; // Wait for serial port to be available
Serial.println(“LoRa Simple_Encrypted Client”);
if (!rf95.init())
Serial.println(“LoRa init failed”);
// Setup ISM frequency
rf95.setFrequency(frequency);
// Setup Power,dBm
rf95.setTxPower(13);
myCipher.setKey(encryptkey, sizeof(encryptkey));
Serial.println(“Waiting for radio to setup”);
delay(1000);
Serial.println(“Setup completed”);
>
void loop()
<
uint8_t data[HWMessageLen+1] = <0>;
for(uint8_t i = 0; i 
OK, here is what I did to get it compiling.
I went here: https://github.com/kostko/arduino-crypto
And downloaded that library, unzipped it into my Arduino/libraries folder, and renamed the enclosing folder to from arduino-crypto-master to just Crypto.
(the Arduino IDE library manager gave me a different library than that it seems – which didn’t have the Speck.h file)
Then, as per the comments in your sketch, I uncommented that line in the RadioHead.h file (it was like ALL the way at the bottom – a couple lines up)
Then I was able to verify this sketch ok.
sketch_oct15a:5:31: fatal error: LiquidCrystal_I2C.h: No such file or directory
#include
compilation terminated.
exit status 1
LiquidCrystal_I2C.h: No such file or directory
Sir I am facing this problem whenever I am trying to upload this program – Arduino 1.8.19 with “NodeMCU 1.0(ESP-12E Module)”-ESP8266 Boards (2.5.2)
Have you installed the LiquidCrystal_I2C library?
To install it, in the Arduino IDE you would go to “Tools > Manage Libraries” and then search for that library and click install.
I still have this error! I did 10-check, and nothing! Keypad.h is orange, it’s like Arduino sees it, but NO! I have this error:
Arduino: 1.8.12 (Windows 10), Board: “Arduino Uno”
swanky_juttuli1:1:10: fatal error: Keypad.h: No such file or directory
exit status 1
Keypad.h: No such file or directory
This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.
Help me please.
Hmmm – do you have multiple keypad libraries installed?
Источник
Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.
How to tell the compiler where to find it
g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to foo.cc (assume you are compiling from the directory where foo.cc is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft’s compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar" is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.
This is true of both forms, include <> and incude "".
Difference between #include <bar> and #include "bar"
Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc:
#include "list"
....
For this, your compiler will #include the file list in your project folder, because it currently compiles main.cc and there is that file list in the current folder.
But with main.cc:
#include <list>
....
and then g++ main.cc, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
Details on <>/""-priorities and -I
According to the gcc-documentation, the priority for include <> is, on a «normal Unix system», as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; […].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list" example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.
It’s 11 PM on a Wednesday. You’ve just spent three hours toiling on your next Arduino project, and FINALLY, you’re ready to give your sketch a whirl. You hit upload, palms sweaty with anticipation to see all your hard work come to fruition. It’s then you see the error:
No such file or directory.
Surely this is a chance aberration. “Nothing to worry about,” you mutter, sleep-starved and semi-delirious as you hit upload again. And once more, those maddening words, “no such file or directory,” stare back at you in hostile gaslighting mockery.
Have you been here?
If you’re trying to run an Arduino sketch but keep coming across the “no such file or directory” error, don’t worry. This is actually a pretty common problem, and there are two easy fixes that almost always work.
Keep on reading. We’ll show you what they are.
No such file error!
Error messages can be such a pain. They do, however, serve a useful purpose by telling us something about what went wrong. At first glance, the no such file or directory error is particularly maddening because it seems to break that useful purpose rule. Of course there’s a file or directory! You just made the thing, and it’s right there, tucked inside a directory.
But hold up, let’s take a closer look. 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.”
Click on that now. You probably won’t fall off your chair to learn that by clicking that button, you just copied the error message from the little window at the bottom of The Serial Monitor’s UI to the clipboard of your computer.
This copy feature is ridiculously useful. You could, for example, paste the error message into Google and learn more about the error. Or you could take advantage of the active Arduino community by asking for help in a forum. For this situation, however, we can be a bit more basic. All we’re going to do is take a closer look at what the message is actually saying. To do that, just fire up your PC’s text editor and paste it into the blank screen.
Decoding the no such file error
Here it is, that pesky error in all its freshly pasted glory.
I’ll break it down for you line by line.
- The first line is easy. It’s just describing the Arduino version in use, what operating system is running, and which board you have selected.
- Line 2 begins to zero in on the problem.
- The first bit, “knob,” is referring to the name of the program. This is your sketch, basically.
- The second bit is what usually begins to confuse people, but it’s easy once you know. The “10” in this example is telling you the error occurred on line 10 of your sketch. The “19” is telling you the length of the line of code in spaces and characters. The first number is usually the more helpful of the two because you can use it to locate the error in your sketch.
- Then we get to the smoking gun of the error. It says, “servo.h: No such file or directory”.
So this thing, “Servo.h.” That’s the thing we need to fix, and thanks to line 2, we know where to find it. Line 10. It’s always line 10.
Now that we know what’s going on a bit better, let’s get down to the business of implementing a fix.
The error of our ways
Let’s lay down some scrutiny on this accursed line 10.
It says “#include <servo.h>”
When we verify this code, this line is telling the Arduino IDE compiler, “Hey, for this program to work, you need to go get this file called servo.h”.
Let’s say you had a label-making machine, and you wanted to use it to print some cool motivational labels, like “Success!” and “Keep Trying!” and “Look, Nachos!” To make that happen, you’ll first have to load in a roll of labels. No roll of labels? Well, then the label maker isn’t gonna work.
The sketch you’re trying to upload is like the label maker. The file (in our example, the file named “servo.h”) is the roll of labels.
So the error message actually is saying something useful. It’s saying, “Hey programmer, you said I needed this other file. Well, I looked for it and it’s not there. What gives?”
Now we know the error message isn’t complete gibberish, let’s look at the two most common scenarios that cause it.
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 (as with the example below) perhaps you capitalized the wrong letters.
So “servo.h” should actually have a capital “S.” In full and with correct capitalization, it should read, “Servo.h.” You’ll notice above that the word servo changes color when it’s correctly capitalized. That color change signifies that the library name “Servo” is recognized as a “keyword” in the Arduino IDE.
Keep in mind that might not be the case for all the libraries you’re using. In other words, the color change won’t always indicate you’re using the right spelling or capitalization, but it’s often a helpful visual reminder.
Oh, and it’s probably good to mention that everyone in the history of Arduino programming has misspelled or incorrectly capitalized a word at some point. It’s amazing how long you can stare at a line of code and miss something like that.
So don’t sweat it.
Scenario 2 – Missing files
This brings us to the next common scenario for the “no such file or directory” error.
So often, working with Arduinos involves taking code that someone else has developed and shared online and then tailoring it to your project. That’s part of what makes it so easy to get stuff done with Arduino. One problem that frequently happens when we do that, however, is we accidentally introduce code without a matching file.
An easy way to check to see if you have the file a sketch is looking for is to navigate to Sketch > Include Library from within the Arduino IDE. 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 a library with the exact same name. If you don’t see the file name there, this means the library isn’t installed. You’ll have to add that library before the sketch will compile without errors.
So, how do you add that library?
The easiest way is to go to Sketch > Include Library > Manage Libraries. The Arduino IDE will open up a dialogue box from which you can search for the library you need.
Make sure you type the exact word that matches the #include line. Once you find the missing library, go ahead and click Install. The Arduino IDE will let you know that it’s installing the library you requested and updating the software accordingly.
Next, just double-check that the library has been successfully installed by going to Sketch > Include Library. You should see your new library in the dropdown list.
Good news! If the library is there, you should now be able to compile your sketch error-free.
Other library locations
OK, there’s one little fly in the ointment. How do these dang ointment flies always manage to complicate things so?
Here’s the thing. Not all libraries live in this convenient pop-up window inside the Arduino IDE. The Arduino community is bubbling with clever ideas, but cleverness (unlike processed cheese) doesn’t always come in conveniently standardized, individually wrapped slices. There are tons of different ways to find Arduino libraries on the web.
If you’re downloading or copying a program from the internet, just go to the page where you got that program and take a close look at the library the author is referencing. They may, for example, have a link to GitHub, which is a place where people keep a lot of code libraries.
Wherever you find it, usually the library will be included in a .zip file package. Once you’ve downloaded the .zip file, fire up the Arduino IDE and go to Sketch > Include Library > Add .ZIP library. Then navigate to the location you downloaded the file and select it. Assuming no additional ointment flies invade your workflow, the Arduino IDE will pop up the message “Library added to your libraries” just above the dark area where the original “no such file or directory” error appeared.
Now it’s business as usual! Just go to Sketch > Include Library, and the new library will appear in the drop-down list.
As the dyslexic Frenchman once said to the oversized violinist: “Viola!”
You now know not one but two ways to add a new library. What a time to be alive!
Review
A quick recap, then.
We’ve looked at the two main scenarios that cause the “no such file or directory” error to appear after you compile your sketch:
- The fat fingers phenomenon: Check your spelling and capitalization! If you wrote the sketch, there’s a mighty good chance you introduced a tiny error. And don’t beat yourself up over it! Literally every coder has done this.
- The missing files mixup: Failing that, if you copied code from someone else check that you have the correct libraries installed. Don’t see your library? Install it using the method described above, and you should be good to go.
There may be no such thing as a free lunch, a coincidence, or a luck dragon. But rest assured. Your files and directories? They’re alive and well.
Introduction
In this intermittent series, I’ll be looking at the most common error messages your C++ compiler (and linker) can produce, explaining exactly what they mean, and showing how they can be fixed (or, better still avoided). The article will specifically talk about the errors produced by the GCC command line compiler, but I’ll occasionally provide some coverage of Microsoft C++ as well. The articles are aimed at beginner to intermediate C++ programmers, and will mostly not be OS-specific.
Error Messages 101
Compiler error messages from the GCC g++ compiler generally look like something this:
main.cpp: In function 'int main()': main.cpp:4:12: error: 'bar' was not declared in this scope
which was produced by this code:
int main() {
int foo = bar;
}
The first line of the error says which function the following error(s) is in. The error message itself comes in four main parts; the file the error occurs in, the line number and character offset at which the compiler thinks the error occurs, the fact that it is an error, and not a warning, and the text of the message.
As well as error, the compiler can also produce warnings. These are usually about constructs that, while not being actually illegal in C++, are considered dubious, or constructs that the compiler has extensions to cover. In almost all cases, you don’t want to use such constructs, and you should treat warnings as errors; in other words, your code should always compile with zero warnings. You should also increase the level of warnings from the compiler’s default, which is usually too low. With g++, you should use at least the -Wall and -Wextra compiler options to do this:
g++ -Wall -Wextra myfile.cpp
No such file or directory
The error I’m looking at today most commonly occurs when you are including a header file using the preprocessor #include directive. For example, suppose you have the following code in a file called myfile.cpp:
#include "myheader.h"
and you get the following error message:
myfile.cpp:1:22: fatal error: myheader.h: No such file or directory compilation terminated.
What could be causing it? Well, the basic cause is that the compiler cannot find a file called myheader.h in the directories it searches when processing the #include directive. This could be so for a number of reasons.
The simplest reason is that you want the compiler to look for myheader.h in the same directory as the myfile.cpp source file, but it can’t find it. this may be because you simply haven’t created the header file yet, but the more common reason is that you either misspelled the header file name in the #include directive, or that you made a mistake in naming the header file when you created it with your editor. Look very closely at the names in both the C++ source and in your source code directory listing. You may be tempted to think «I know that file is there!», but if the compiler says it isn’t there, then it isn’t, no matter how sure you are that it is.
This problem is somewhat greater on Unix-like system, such as Linux, as there file names are character case sensitive, so Myheader.h, MyHeader.h, myheader.h and so on would all name different files, and if you get the case wrong, the compiler will not look for something «similar». For this reason, a very good rule of thumb is:
Never use mixed case when naming C++ source and header files. Use only alphanumeric characters and the underscore when naming C+++ files. Never include spaces or other special characters in file names.
Apart from avoiding file not found errors, this will also make life much easier if you are porting your code to other operating systems which may or may not respect character case.
The wrong directory?
Another situation where you may get this error message is if you have split your header files up from your C++ source files into separate directories. This is generally good practice, but can cause problems. Suppose your C++ project is rooted at C:/myprojects/aproject, and that in the aproject directory you have two sub-directorys called src (for the .cpp files) and inc (for the header files), and you put myfile.cpp in the src directory, and myheader.h in the inc directory, so that you have this setup:
myprojects
aproject
inc
myheader.h
src
myfile.cpp
Now if you compile the source myfile.cpp from the src directory, you will get the «No such file or directory» error message. The C++ compiler knows nothing about the directory structures of your project, and won’t look in the inc directory for the header. You need to tell it to look there somehow.
One thing some people try when faced with this problem is to re-write myfile.cpp so it looks like this:
#include "c:/myprojects/aproject/inc/myheader.h"
or the slightly more sophisticated:
#include "../inc/myheader.h"
Both of these are a bad idea, as they tie your C++ code to the project’s directory structure and/or location, both of which you will probably want to change at some point in the future. If the directory structure does change, you will have to edit all your #include directories.The better way to deal with this problem is to tell the compiler directly where to look for header files. You can do that with the compiler’s -I option, which tells the compiler to look in the specified directory, as well as the ones it normally searches:
g++ -Ic:/myprojects/aproject/inc myfile.cpp
Now the original #include directive:
#include "myheader.h"
will work, and if your directory structure changes you need only modify the compiler command line. Of course, writing such command lines is error prone, and you should put such stuff in a makefile, the use of which is unfortunately outside the scope of this article.
Problems with libraries
Somewhat similar issues to those described above can occur when you want to use a third-party library. Suppose you want to use the excellent random number generating facilities of the Boost library. If you are copying example code, you may well end up with something like this in your C++ source file:
#include "boost/random.hpp"
This will in all probability lead to yet another «No such file or directory» message, as once again the compiler does not know where «boost/random.hpp» is supposed to be. In fact, it is one of the subdirectories of the Boost installation, and on my system I can get the #include directive to work using this command line:
g++ -Ic:/prog/boost1461 myfile.cpp
where /prog/boost1461 is the root directory for my specific Boost library installation.
Can’t find C++ Standard Library files?
One last problem that beginners run into is the inability of the compiler to find header files that are part of the C++ Standard Library. One particular favourite is this one:
#include <iostream.h>
where you are learning C++ from a very, very old book. Modern C++ implementations have not contained a file called iostream.h for a very long time indeed, and your compiler is never going to find it. You need to use the correct, standard names for such headers (and to get a better book!):
#include <iostream>
If this still fails, then there is almost certainly something very wrong with your GCC installation. The GCC compiler looks for Standard Library files in a subdirectory of its installation, and locates that directory relative to the directory containing the compiler executable, so if the Standard Library headers are available, the compiler should always find them.
Conclusion
This article looked at the «No such file or directory» message of the GCC C++ compiler. If you get this message you should:
- Remember that the compiler is always right in situations like this.
- Look very closely at the file name to make sure it is correct.
- Avoid naming file using mixed-case or special characters.
- Use the -I compiler option to tell the compiler where to look for files.
- Make sure that GCC is correctly installed on your system.
Hi i have a problem in linux terminal line. So i tried compiling a file to .o like this
gcc -c palindrome.c
and the error is
palindrome.c:2:21: fatal error: reverse.h: No such file or directory
compilation terminated.
The file reverse.h indeed is in the directory because i copied everything from lab2 directory to lab 3. So why is it saying that? Thanks for the help
cscstuff@ubuntu:~/inlab2$ ls -l
total 32
-rwxrwxr-x 1 cscstuff cscstuff 8784 Oct 1 08:26 main1
-rw-rw-r-- 1 cscstuff cscstuff 338 Oct 1 08:20 main1.c
-rw-rw-r-- 1 cscstuff cscstuff 1888 Oct 1 08:24 main1.o
-rw-rw-r-- 1 cscstuff cscstuff 204 Oct 1 08:26 reverse.c
-rw-rw-r-- 1 cscstuff cscstuff 84 Oct 1 08:19 reverse.h
-rw-rw-r-- 1 cscstuff cscstuff 1472 Oct 1 08:26 reverse.o
cscstuff@ubuntu:~/inlab2$ cd
cscstuff@ubuntu:~$ cd inlab3
cscstuff@ubuntu:~/inlab3$ ls -l
total 16
drwxrwxr-x 2 cscstuff cscstuff 4096 Oct 1 08:33 inlab2
-rw-rw-r-- 1 cscstuff cscstuff 247 Oct 1 09:21 main2.c
-rw-rw-r-- 1 cscstuff cscstuff 297 Oct 15 11:01 palindrome.c
-rw-rw-r-- 1 cscstuff cscstuff 51 Oct 1 08:34 palindrome.h
cscstuff@ubuntu:~/inlab3$ gcc -c palindrome.c
palindrome.c:2:21: fatal error: reverse.h: No such file or directory
compilation terminated.
cscstuff@ubuntu:~/inlab3$
Archemar
30.6k18 gold badges69 silver badges104 bronze badges
asked Oct 15, 2017 at 18:15
7
From inlab3 either
-
add
-I../inlab2to compiler (e.g.gcc -I../inlab2 -c palindrome.c, this will tell gcc to look in ../inlab2 for the header file) -
use
#include "../inlab2/reverse.h"in include line (this will give relative path for the header file) -
copy from
inlab2cp ../inlab2/reverse.h .(this will make a copy of the header file available ininlab3)
Kusalananda♦
307k35 gold badges598 silver badges896 bronze badges
answered Oct 15, 2017 at 19:03
ArchemarArchemar
30.6k18 gold badges69 silver badges104 bronze badges
|
1 / 1 / 1 Регистрация: 09.04.2016 Сообщений: 98 |
|
|
1 |
|
|
27.09.2016, 18:26. Показов 15180. Ответов 8
Из-за чего возникает такая ошибка? Или он не видит библиотеку, если не видит, то как подключить? Миниатюры
__________________
0 |
|
553 / 361 / 206 Регистрация: 27.11.2014 Сообщений: 1,043 |
|
|
27.09.2016, 18:28 |
2 |
|
попробуй без «.h»
1 |
|
1 / 1 / 1 Регистрация: 09.04.2016 Сообщений: 98 |
|
|
27.09.2016, 18:35 [ТС] |
3 |
|
Пробовал, результат такой: Миниатюры
0 |
|
553 / 361 / 206 Регистрация: 27.11.2014 Сообщений: 1,043 |
|
|
27.09.2016, 18:40 |
4 |
|
Paterul, Скобку что-ль фигурную забыл?
1 |
|
1 / 1 / 1 Регистрация: 09.04.2016 Сообщений: 98 |
|
|
27.09.2016, 18:45 [ТС] |
5 |
|
ture, Это да, но что-то все равно не проходит Миниатюры
0 |
|
Paterul 1 / 1 / 1 Регистрация: 09.04.2016 Сообщений: 98 |
||||
|
27.09.2016, 18:49 [ТС] |
6 |
|||
|
Может у вас работает или те же ошибки?
0 |
|
ture 553 / 361 / 206 Регистрация: 27.11.2014 Сообщений: 1,043 |
||||
|
27.09.2016, 18:54 |
7 |
|||
|
РешениеЗабыл пространство имен подсветить:
1 |
|
1 / 1 / 1 Регистрация: 09.04.2016 Сообщений: 98 |
|
|
27.09.2016, 19:03 [ТС] |
8 |
|
ture, Это для того, чтобы работала библиотека iostream?
0 |
|
553 / 361 / 206 Регистрация: 27.11.2014 Сообщений: 1,043 |
|
|
28.09.2016, 08:50 |
9 |
|
РешениеPaterul, iostream — это файл, который добавляет в пространство std всякие имена (cin, cout и т.д.), чтоб можно было пользоваться ими (к примеру, std::cin). А using namespace std — это для сокращения записи (чтоб просто писать cin? т.е. без std:
1 |












Сообщение было отмечено Paterul как решение
.