How to include file with makefile?

Viewed 49

i'm new to compiling c ++ programs with makefile on linux. trying to include a header file inside another the compiler gives me the following error:

In file included from main.cpp:5:
send_file.hpp:2:10: fatal error: connection.hpp: No such file or directory
    2 | #include <connection.hpp>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.
make: *** [makefile:5: main.o] Error 1

This is the send_file.hpp file:

#include <string>
#include <connection.hpp>
using namespace std;

class SendFile
{
public:
    static bool send_file(string filename, Connection *connection);
};

This is the connection.hpp file

#pragma once

#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <exception>
using namespace std;
#define PORT 12345

class Connection
{
public:
    Connection();
    Connection(string ip_addr, string filename);
    void set_ip_address(string ip_addr);
    void set_filename(string filename);
    string get_ip_address();
    string get_filename();
    bool open_connection();
    bool send_string(string msg);
private:
    string ip_addr;
    string filename;
    sockaddr_in server_addr;// server's IP address
    int client_sock;
};

and, finally this is makefile

output: main.o ipaddress.o file.o connection.o send_file.o
    g++ main.o ipaddress.o file.o connection.o send_file.o -o output

main.o: main.cpp
    g++ -c main.cpp

ipaddress.o: ipaddress.cpp ipaddress.hpp
    g++ -c ipaddress.cpp

file.o: file.cpp file.hpp
    g++ -c file.cpp

connection.o: connection.cpp connection.hpp
    g++ -c connection.cpp

send_file.o: send_file.cpp send_file.hpp
    g++ -c send_file.cpp

target: dependencies
    action

clean:
    rm *.o

thank you very much for helping

1 Answers

I usually employ the template below for Makefile (adapted to the names of your files).

I believe main.o should be created last, after all the dependencies it uses. Same for modules that are dependencies of some other modules.

CXX = g++
CXXFLAGS = -Wall

OBJECTS = ipaddress.o file.o connection.o send_file.o main.o

main: $(OBJECTS)
        $(CXX) $(CXXFLAGS) -o $@ $^
        
$(OBJECTS): ipaddress.hpp file.hpp connection.hpp send_file.hpp

Related