I have a file like this: (p1.c)
1 #include <iostream>
5
6 int main(int argc, char* argv[]) {
7 std::cout << "No iostream\n";
8 return 0;
9 }
And I try to compile with a simple makefile like this:
1 app: p1.o
2 g p1.o -o p1
3
4 clean:
5 rm *.o p1 p2
Running make
yields this:
p1.c:1:10: fatal error: iostream: No such file or directory
#include <iostream>
^~~~~~~~~~
compilation terminated.
<builtin>: recipe for target 'p1.o' failed
make: *** [p1.o] Error 1
But running g p1.c
works fine, no issues.
Am I doing something wrong in the make file? I've had no other troubles with libraries besides iostream.
CodePudding user response:
You have only specified a Makefile rule to link the object file to an executable. You haven't actually specified a rule to compile the source code file to an object file.
Therefore make
will try to use an implicit rule to build the object file p1.o
from p1.c
.
Because p1.c
has the file ending .c
it will assume that the file is C source code and call cc
to compile it, which should be a C compiler, not a C compiler.
In C there is no <iostream>
and so the compilation fails.
Change the file name from p1.c
to p1.cpp
or p1.cxx
or p1.cc
or some of the other conventional file endings for C . It is not only confusing to make
, but also confusing to other programmers, when a .c
file doesn't actually contain C source code.