Suslik
Suslik

Reputation: 1071

include class and compile with g++

Im a beginner in C++ and working with unix. So here is my question.

I`ve written few lines in the main-function, and i needed a function, that is defined in the c_lib - library.

main.cpp:

#include <iostream>
#include "c_lib.cpp"

int main() 
{
    return 0;
}

i want to execute it on the terminal, so i wrote

g++ -c c_lib.cpp

g++ -c main.cpp

g++ -o run c_lib.o main.o

Until here, there is no error report.

Then

./run

I get the error

error: ./run: No such file or directory

What's wrong?

Upvotes: 1

Views: 2447

Answers (2)

Baldrickk
Baldrickk

Reputation: 4409

Including a .cpp is not usually done, usually only headers are included. Headers usually contain the declarations that define the interface to the code in the other .cpp
Can you show us the source of c_lib? That may help.

As the source of c_lib is #included, there is no need to compile it seperately. In fact this can/will cause errors (multiple definitions being the first to come to mind). You should only need to do:

g++ -o run main.cpp

to compile your code in this case.
(When using a header (.h), you will need to compile the implementation (.cpp) seperately)

Compile with warnings turned on:

g++ -Wall -Wextra -o run main.cpp

and you will get more output if there are problems with your code.

Is the run file being output by gcc? You can test by calling ls in the terminal (or ls run to only show the executable if it is present).

If the executable is present, it could be that it isn't marked as runnable. I'll go into that if it is a problem as it is outside the general scope of the site (though still related)

Upvotes: 6

Slava
Slava

Reputation: 44248

First of all you should not include source file into another source. You should create a header file and put declarations there (that allows main() to call functions from c_lib.cpp or use global variables if any)

When you run g++ you have to look into it's output, if operation succeed or not. In your case it failed so executable run was not created.

Usually you do not call compiler manually but write a makefile and let make utility to call g++.

Upvotes: 0

Related Questions