Definition and implementation in different locations

Asked

Viewed 71 times

0

Hello. I am having doubts when implementing a header in folders with different paths. I am placing my header in a folder called "include" and implementations in a folder called "src". To solve this problem, I am doing the following in the implementation: #include "../include/header.h"

My doubt is that, when seeing many codes available on the internet, do not use the ".. /" to go to the directory, where many only include the header name. For example: #include "header.h"

I would like to know how this is possible as when I don’t path to the correct directory, I get file errors not found. Including, even the ready codes that low on the internet I need to fix the directory of the files as I get the same error.

  • What method do you use to compile the software? Make (Makefile), others?

  • I use the same terminal, I haven’t learned to use Makefiles yet.

1 answer

1


Just to serve as a small example, suppose the structure of your project is as follows::

Raiz
|-inc
| | foo.h
|-src
| | main.cpp
|-bin
  |

Contents of the files

foo. h

#include<string>

class Foo {

public:
    Foo(std::string nome) : nome_(nome) {}
    std::string getNome() { return nome_; }
private:
    std::string nome_;

};

main.cpp

#include<iostream>
#include "foo.h"

int main(int argc, char *argv[]) {

    Foo foo("André");
    std::cout << "Hello " << foo.getNome() << std::endl;

    return 0;

}

To compile this small project directly on the command line you can execute the following command:

g++ -Iinc/ -o bin/foo src/main.cpp

The most important part is to indicate to the compiler, with the flag -I additional directories to find files in. This is the directory inc/.

The result of the command will put the executable in the directory bin/

Although this is enough for a small project, I would recommend that you read the topic about Makefile or equivalent.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.