user4158347
user4158347

Reputation:

G++ Not Finding Included .cpp Files When Compiling

Inkey.cpp and Key.cpp are in the same directory, /root/src.

Compile.bat is in /root.

When I run Compile.bat, I am given the message "Key.cpp: No such file or directory".

Thanks in advance for any advice.

Inkey.cpp

#include <iostream>
#include <Key.cpp>

using namespace std;

int main(int argc, char *argv[]) {
    cout << "Hello from InKey" << endl;

    Key key1;

    return 0;
}

Key.cpp

#include <iostream>

using namespace std;

class Key {
    public:
        Key() {
            cout << "New Key instantiated." << endl;
        };
};

Compile.bat

@ECHO OFF

g++ "src/Inkey.cpp" -o "out/InKey.exe"

"out\Inkey.exe"

Upvotes: 0

Views: 977

Answers (2)

kesarling
kesarling

Reputation: 2228

First off, rename Key.cpp to Key.h. Put the declaration in Key.h. Then put the definition in Key.cpp (Don't forget to include Key.h here). Then include your Key.h in all files using Key objects.
Now, compile them with g++ -o filename.out file1.cpp file2.cpp -O3 -Wall
Also, learn to use boilerplate code

P.S. as @SoronelHaetir has suggested, use "" to include custom header files

Upvotes: 0

SoronelHaetir
SoronelHaetir

Reputation: 15162

Look up the difference between #include "filename" and #include <filename>. The former starts at the current directory, the latter uses a search path (or set of such paths). (Note that #include "filename" will fall back on the search strategy of #include <filename> if no file is found starting from the current directory).

Also, you do not usually include .cpp files, you pass them as separate arguments to the compiler and then combine them using the linker.

Upvotes: 1

Related Questions