简体   繁体   中英

Why can't Makefile find include directories

I can't seem to include a header in my test program using a Makefile.

I've attempted to try relative paths using -I with no luck. I'm new to Make and for some reason I am having a hard time understanding it's usage.

my code, test.cpp

#include <iostream>
#include <results/enumTest.h>

int main()
{
   return 0;
}

and my Makefile:

CFLAGS = -Wall -g -Wextra -Wpedantic -std=gnu++11 -m64 -Iinclude

test: test.o
    gcc $(CFLAGS) -I/.. -o  test test.o 

test.o: test.cpp
    gcc $(CFLAGS) -I/.. -c test.cpp

my directory structure:

/testDir/
  ./results/enuMtest.h
  ./test/test.cpp
  ./test/Makefile

I would hope that I could compile and then run the test software using a Makefile. This is more or less a tutorial for me.

Your include path -I/.. is invalid. You're trying to access the parent directory of the root directory, which cannot exist. Change your Makefile to use relative paths instead with -I..

This will access the parent directory as intended:

CFLAGS = -Wall -g -Wextra -Wpedantic -std=gnu++11 -m64 -Iinclude

test: test.o
    g++ $(CFLAGS) -I.. -o  test test.o # Change here

test.o: test.cpp
    g++ $(CFLAGS) -I.. -c test.cpp # ...and here

Note the removed slashes.

EDIT: As commented by @Lightness, you should include non-system headers with "header.h" rather than <header.h> . Additionally, since you are trying to compile a C++ program, it is recommended to use g++ instead of gcc (I've updated this in the snippet above).

There are several improvements possible.

  • You try to set the include path to the parent dir of / which is /.
  • You try to compile a c++ program using gcc but not g++
  • You don't need (it would still work) to set an include path, when linking. (test: test.o)
  • Since there is no directory named include in the filetree you specified, you also don't need -Iinclude in the CFLAGS
  • Usually the C++ variant of CFLAGS is named CXXFLAGS, but I did not change it in the modified example below.

A corrected makefile would be:

CFLAGS = -Wall -g -Wextra -Wpedantic -std=gnu++11 -m64

test: test.o
    g++ $(CFLAGS) -o  test test.o 

test.o: test.cpp
    g++ $(CFLAGS) -I.. -c test.cpp

As an additional note:

#include "" instead of #include <> would also work. The difference is, that "" searches the included file relative from the location of the current source file, while <> uses the directories you specify using -I . Find more details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM