I have a program: foo.cpp and bar.cpp and have created a Makefile to compile them.
This is how it(Makefile) looks:
CC=g++
CFLAGS=-c
foo.o: foo.cpp
$(CC) $(CFLAGS) foo.cpp -o foo
all: foo.o bar.o
bar.o: bar.cpp
$(CC) $(CFLAGS) bar.cpp -o bar
Now, when I run make all, it compiles and I have the output files there but when I run ./foo it gives me this error--> bash: ./foo: Permission denied
However if I do g++ foo.cpp and then do ./a.out then it runs.
I have seen the similar questions like: https://askubuntu.com/questions/466605/cannot-open-output-file-permission-denied and tried the solution but it did not work.
I don't understand why this is happening. Can someone please help(I am new to Makefiles)?
Thanks
Solution and Mistakes done:
1)using -c flag
, it created an output file and not an executable file which I was trying to execute.
2)for more information , here is an answer on linkers: What's an object file in C?
The file foo
is the object file generated from foo.cpp
. Object files can of course not be executed, since they are not complete programs.
Since you don't give a specific name for the executable, the default is a.out
on POSIX environments (like Linux).
If you want a specific file-name then you need to add a command to create it. And make sure it doesn't clash with an existing object file.
I recommend you change your whole Makefile
to something much more simple, like this:
all: foo
foo: foo.o bar.o
$(CXX) foo.o bar.o -o foo
That's all that is needed. The object files will be created, with the correct names , from implicit rules.
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.