Definition and implementation in different places

0

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

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

I would like to know how this is possible, because when I do not get to the correct directory, I get file errors not found. Even the ready codes that down on the internet I need to fix the files directory as I get the same error.

    
asked by anonymous 05.07.2015 / 08:20

1 answer

1

Just as a small example, let's say your project structure is as follows:

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

File content

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 tell the compiler, with the flag -I additional directories where to look for the files. In this case it is the directory inc/ .

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

Although this is sufficient for a small project, I would recommend that you read a topic in Makefile or equivalent.

    
05.07.2015 / 13:11