Test c 1 10 fatal error freeimage h no such file or directory

Сообщение об ошибке: 'FreeImage.h' file not found CmakeList (я на MAC): cmake_minimum_required(VERSION 3.10) set(PROJECT_NAME KinectFusion) project(${PROJECT_NAME}) set (CMAKE_CXX_STANDARD 14) set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) add_definitions(-DPROJECT_DIR="${P....

Сообщение об ошибке: 'FreeImage.h' file not found

CmakeList (я на MAC):

cmake_minimum_required(VERSION 3.10)
set(PROJECT_NAME KinectFusion)
project(${PROJECT_NAME})

set (CMAKE_CXX_STANDARD 14)
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH})
add_definitions(-DPROJECT_DIR="${PROJECT_SOURCE_DIR}")

set(EXECUTABLE_OUTPUT_PATH bin)
set(LIBRARY_OUTPUT_PATH lib)

# for some reason clang doesn't include them in Wall whereas gcc does, so include them explicitly.
SET(EXTRA_WARNING_FLAGS "-Wsign-compare")
SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
SET(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG") # -march=native")

SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -g -DNDEBUG -ftree-vectorize")
SET(CMAKE_CXX_FLAGS " -ftemplate-backtrace-limit=0 -Wall ${EXTRA_WARNING_FLAGS} ${CMAKE_CXX_FLAGS}")

find_package(FreeImage REQUIRED)

#find_package(realsense2 REQUIRED)
#include_directories(${realsense2_INCLUDE_DIRS})

#adds gitsubmodules
add_subdirectory(extern)
### if CMAKE Build Time
#adds our KinectFusion Lib
add_subdirectory(FusionLib)

#<-------Stuff for directly building an Application----->
set(APP_ONE ${PROJECT_NAME} )
add_executable(${APP_ONE} main.cpp)
#target_link_libraries
target_link_libraries (${APP_ONE} kfusion eigen ${FREEIMAGE_LIBRARIES} realsense2)
target_compile_features(${APP_ONE} PUBLIC cxx_std_17 )
target_compile_definitions(${APP_ONE} PRIVATE PROJECT_DATA_DIR="${CMAKE_SOURCE_DIR}/data")



### Copy Data to cmake-build, this need to be applied to each new executable###
add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_SOURCE_DIR}/data $<TARGET_FILE_DIR:${PROJECT_NAME}>/data)

Я не могу понять, почему не удается найти FreeImage.h ‘. Я пытался использовать find_package, но это приводит к той же ошибке. Есть какие-нибудь подсказки? Меня также смущает разница между target_include_directories и target_link_libraries.

РЕДАКТИРОВАТЬ: вывод консоли с помощью find_package (ТРЕБУЕТСЯ FreeImage)

rm -r build && mkdir build && cd build && cmake .. && make
-- The C compiler identification is AppleClang 11.0.3.11030032
-- The CXX compiler identification is AppleClang 11.0.3.11030032
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc - works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found FreeImage
--   Includes : /usr/local/include
--   Libraries : /usr/local/lib/libfreeimage.dylib
-- Submodule update
-- Configuring done
-- Generating done
-- Build files have been written to: BLABLA/KinectFusion/build
Scanning dependencies of target kfusion
[  8%] Building CXX object FusionLib/CMakeFiles/kfusion.dir/src/icp.cpp.o
[ 16%] Building CXX object FusionLib/CMakeFiles/kfusion.dir/src/VirtualSensor.cpp.o
In file included from BLABLA/FusionLib/src/VirtualSensor.cpp:1:
In file included from ***/FusionLib/include/VirtualSensor.h:9:
BLABLA /FusionLib/include/FreeImageHelper.hpp:9:10: fatal error: 'FreeImage.h' file not found
#include <FreeImage.h>
         ^~~~~~~~~~~~~
1 error generated.
make[2]: *** [FusionLib/CMakeFiles/kfusion.dir/src/VirtualSensor.cpp.o] Error 1
make[1]: *** [FusionLib/CMakeFiles/kfusion.dir/all] Error 2
make: *** [all] Error 2

1 ответ

Лучший ответ

После find_package(FreeImage REQUIRED)

Вставлять

include_directories(${FREEIMAGE_INCLUDE_DIRS})

Или

include_directories(${FreeImage_INCLUDE_DIR})

(в зависимости от того, какой модуль FindFreeImage.cmake вы используете)

И он должен работать. В качестве альтернативы используйте include_directories(/usr/local/include)

find_package(<pkg-name> REQUIRED) просто гарантирует, что этот пакет установлен в вашей системе. Он не изменяет вашу сборку автоматически. Пакет Freeimage установлен в вашей системе, но «/ usr / local / include» не указан в пути поиска в вашем заголовке. Чтобы добавить каталог к ​​пути поиска заголовка, используйте команду cmake include_directories(). См. Документацию по cmake здесь: https://cmake.org/cmake/help/ последняя / команда / include_directories.html


1

MatzZze
22 Июл 2020 в 21:32

ArtyomTank

1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

1

10.04.2019, 12:21. Показов 5440. Ответов 26

Метки c++ sfml, sfml (Все метки)


Компилятор выдаёт ошибку

что вводил
E:MinGWmingw32bin>

Windows Batch file
1
g++ -static -o -LE:libsSFMLnotBuildSFML-2.5.1include -LE:libsSFMLnotBuildSFML-2.5.1lib -LE:libsSFMLnotBuildSFML-2.5.1bin -lsfml-window -lsfml-graphics -lsfml-system -static -libcc -static -libstdc++ E:SFMLProjectsTesttestSFML.cpp

ошибка:
In file included from E:SFMLProjectsTesttestSFML.cpp:1:
E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/System.hpp:32:10: fatal error: SFML/Config.hpp: No such
file or directory
#include <SFML/Config.hpp>
^~~~~~~~~~~~~~~~~
compilation terminated.

при таком коде

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/System.hpp>
#include <E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/Window.hpp>
#include <E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/Graphics.hpp>
int main(){
    sf::RenderWindow window(sf::VideoMode({800, 600}),"Test");
    
    window.clear();
    
    sf::CircleShape circle(40);
    circle.setPosition({200,120});
    circle.setFillColor(sf::Color(0xFF,0x0,0x0));
    window.draw(circle);
    
    window.display();
    
    sf::sleep(sf::seconds(20));
}

Заглянув в эти файлы я узнал, что они все выдатут подобную ошибку.
Неужели косяк разработчиков?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Azazel-San

10.04.2019, 12:35

Не по теме:

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

Неужели косяк разработчиков?

Да, наверняка.
Напишите им об этом!



0



1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

10.04.2019, 12:36

 [ТС]

3

А может это таки мой косяк?



0



Azazel-San

10.04.2019, 12:37

Не по теме:

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

А может это таки мой косяк?

Да не, не может быть.



0



1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

10.04.2019, 12:40

 [ТС]

5

Хорошо



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

10.04.2019, 12:45

6

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

-LE:libsSFMLnotBuildSFML-2.5.1include

-I, а не -L
-IE:libsSFMLnotBuildSFML-2.5.1include

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

при таком коде

А уж взять пример с сайта SFML нельзя?

P.S. А далее могут попереть undefined reference, но подождем.



1



ArtyomTank

1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

10.04.2019, 13:01

 [ТС]

7

Написал

Добавлено через 4 минуты
пример с сайта

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <SFML/Graphics.hpp>
 
int main()
{
    // create the window
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
 
    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                window.close();
        }
 
        // clear the window with black color
        window.clear(sf::Color::Black);
 
        // draw everything here...
        // window.draw(...);
 
        // end the current frame
        window.display();
    }
 
    return 0;
}
Windows Batch file
1
2
3
4
5
6
E:MinGWmingw32bin>g++ -static -o -IE:libsSFMLnotBuildSFML-2.5.1include -IE:libsSFMLnotBuildSFML-2.5.1lib -IE:libsSFMLnotBuildSFML-2.5.1bin -lsfml-window -lsfml-graphics -lsfml-system -static -libcc -static -libstdc++ E:SFMLProjectsTesttestSFML.cpp
 
E:SFMLProjectsTesttestSFML.cpp:1:10: fatal error: SFML/Graphics.hpp: No such file or directory
 #include <SFML/Graphics.hpp>
          ^~~~~~~~~~~~~~~~~~~
compilation terminated.

Добавлено через 1 минуту
подкорректировал

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/Graphics.hpp>
 
int main()
{
    // create the window
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
 
    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                window.close();
        }
 
        // clear the window with black color
        window.clear(sf::Color::Black);
 
        // draw everything here...
        // window.draw(...);
 
        // end the current frame
        window.display();
    }
 
    return 0;
}



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

10.04.2019, 13:09

8

ArtyomTank, ключ -o указывает выходной файл. Вы хотите записать результат как -IE:libsSFMLnotBuildSFML-2.5.1include? Что-то сомневаюсь. И да, я показал где поменять -L на -I, но это не значит, что нужно было везде произвести замену. Может сначала всё-таки потренироваться в использовании компилятора?



1



1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

10.04.2019, 14:26

 [ТС]

9

про ключ я знаю просто опечатался



0



ArtyomTank

1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

11.04.2019, 03:25

 [ТС]

10

Windows Batch file
1
2
3
4
5
6
7
8
9
E:MinGWmingw32bin>
g++ E:SFMLprojectsTesttestSFML.cpp -o E:SFMLprojectsTesttestSFML.exe -IE:E:libsSFMLnotBuildSFML-2.5.1include -LE:libsSFMLnotBuildSFML-2.5.1lib -LE:libsSFMLnotBuildSFML-2.5.1bin -lsfml-window -lsfml-graphics -lsfml-system -mwindows -static-libgcc -static-libstdc++
 
In file included from E:SFMLprojectsTesttestSFML.cpp:1:
E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/Graphics.hpp:32:10: fatal error: SFML/Window.hpp: No su
ch file or directory
 #include <SFML/Window.hpp>
          ^~~~~~~~~~~~~~~~~
compilation terminated.

Вроде бы правильно написал или нет?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <E:/libs/SFMLnotBuild/SFML-2.5.1/include/SFML/Graphics.hpp>
 
int main()
{
    // create the window
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
 
    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                window.close();
        }
 
        // clear the window with black color
        window.clear(sf::Color::Black);
 
        // draw everything here...
        // window.draw(...);
 
        // end the current frame
        window.display();
    }
 
    return 0;
}



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

11.04.2019, 06:20

11

ArtyomTank, E:E:



1



1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

12.04.2019, 12:13

 [ТС]

12

Не по теме:

БЛИН, чувствую себя умстнотсталым

Добавлено через 52 секунды

Цитата
Сообщение от Croessmah
Посмотреть сообщение

P.S. А далее могут попереть undefined reference, но подождем.

Ужо таки поперли, что делать?

Добавлено через 7 минут

Добавлено через 1 минуту

Не по теме:

Azazel-San, я наверно не понял твоего сарказма



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

12.04.2019, 13:11

13

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

Ужо таки поперли, что делать?

Линкер что пишет конкретно? Мы ж не должны гадать.
На первой советую убрать ключи -static.
И это тоже целиком под нож: -static -libcc -static -libstdc++.



0



ArtyomTank

1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

12.04.2019, 14:25

 [ТС]

14

вот что

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
E:MinGWmingw32bin>g++ E:SFMLprojectsTesttestSFML.cpp -o E:SFMLprojectsTesttestSFML.exe -IE:
libsSFMLnotBuildSFML-2.5.1include -LE:libsSFMLnotBuildSFML-2.5.1lib -LE:libsSFMLnotBuildS
FML-2.5.1bin -lsfml-window -lsfml-graphics -lsfml-system -mwindows -static-libgcc -static-libstdc++
 
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x7c): undefined reference to `_
imp___ZN2sf6StringC1EPKcRKSt6locale'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0xa2): undefined reference to `_
imp___ZN2sf9VideoModeC1Ejjj'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0xde): undefined reference to `_
imp___ZN2sf12RenderWindowC1ENS_9VideoModeERKNS_6StringEjRKNS_15ContextSettingsE'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x104): undefined reference to `
_imp___ZNK2sf6Window6isOpenEv'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x120): undefined reference to `
_imp___ZN2sf6Window9pollEventERNS_5EventE'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x140): undefined reference to `
_imp___ZN2sf6Window5closeEv'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x152): undefined reference to `
_imp___ZN2sf5Color5BlackE'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x15c): undefined reference to `
_imp___ZN2sf12RenderTarget5clearERKNS_5ColorE'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x16e): undefined reference to `
_imp___ZN2sf6Window7displayEv'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x184): undefined reference to `
_imp___ZN2sf12RenderWindowD1Ev'
C:UsersMILKYW~1AppDataLocalTempccqOBIN0.o:testSFML.cpp:(.text+0x1bd): undefined reference to `
_imp___ZN2sf12RenderWindowD1Ev'
collect2.exe: error: ld returned 1 exit status
 
E:MinGWmingw32bin>



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

12.04.2019, 18:05

15

-lsfml-window -lsfml-graphics

Наоборот: -lsfml-graphics -lsfml-window



0



ArtyomTank

1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

13.04.2019, 00:48

 [ТС]

16

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
E:MinGWmingw32bin>g++ E:SFMLprojectsTesttestSFML.cpp -o E:SFMLprojectsTesttestSFML.exe -IE:libsSFMLnotBuildSFML-2.5.1include -LE:libsSFMLnotBuildSFML-2.5.1lib -LE:libsSFMLnotBuildSFML-2.5.1bin -lsfml-graphics -lsfml-window -lsfml-system -mwindows
 
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x7c): undefined reference to `_
imp___ZN2sf6StringC1EPKcRKSt6locale'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0xa2): undefined reference to `_
imp___ZN2sf9VideoModeC1Ejjj'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0xde): undefined reference to `_
imp___ZN2sf12RenderWindowC1ENS_9VideoModeERKNS_6StringEjRKNS_15ContextSettingsE'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x104): undefined reference to `
_imp___ZNK2sf6Window6isOpenEv'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x120): undefined reference to `
_imp___ZN2sf6Window9pollEventERNS_5EventE'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x140): undefined reference to `
_imp___ZN2sf6Window5closeEv'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x152): undefined reference to `
_imp___ZN2sf5Color5BlackE'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x15c): undefined reference to `
_imp___ZN2sf12RenderTarget5clearERKNS_5ColorE'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x16e): undefined reference to `
_imp___ZN2sf6Window7displayEv'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x184): undefined reference to `
_imp___ZN2sf12RenderWindowD1Ev'
C:UsersMILKYW~1AppDataLocalTempccohpdMy.o:testSFML.cpp:(.text+0x1bd): undefined reference to `
_imp___ZN2sf12RenderWindowD1Ev'
collect2.exe: error: ld returned 1 exit status



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

13.04.2019, 01:06

17

А для своего ли компилятора Вы скачали бинарники?



0



1 / 1 / 0

Регистрация: 21.02.2019

Сообщений: 137

15.04.2019, 11:35

 [ТС]

18



0



3433 / 2812 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

15.04.2019, 13:43

19

Цитата
Сообщение от ArtyomTank
Посмотреть сообщение

я использовал компилятор

Номер какой?



0



Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,517

Записей в блоге: 1

15.04.2019, 17:18

20

ArtyomTank, какая версия? Модель потоков? Исключений и т.д.?
Короче, cmake у тебя есть, скачиваешь исходники SFML, собираешь своим компрлятором и радуешься.



1



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.

Понравилась статья? Поделить с друзьями:
  • Test 1 runtime error
  • Temporary server error please try again later attr5
  • Temporary server error 451
  • Tesselating liquid in world ошибка
  • Temporary error t1 вконтакте реклама что это