-1

I am writing a simple program to compile from the command prompt. There is an app1 program that uses a class located in a separate file. The class sample1 has a header file sample1.h where all the function declarations exist. The sample1.cpp file contains the function definitions.

app1.cpp:

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

using namespace std;

int main()
{
    sample1 t;
    cout<<"The program is ending"<<endl;
    return 0;
}

sample1.h:

#ifndef SAMPLE1_H
#define SAMPLE1_H

class sample1
{       
    public:
    sample1();
};

#endif

sample1.cpp:

#include<sample1.h>
#include <iostream>

using namespace std;

sample1::sample1()
{
    cout<<"This error sucks"<<endl;
}

I am compiling this program using Windows Subsystem for Linux. However, when I try to compile with g++ 'app1.cpp' -o app1, I get this error: enter image description here

I get that the error is telling me that the program cannot find the constructor sample::sample() but why is that? I included the header file in the program. These 3 files all exist in the same folder.

Julian
  • 81
  • 1
  • 11
  • 1
    Can you point out exactly at which step you are compiling and linking with your second `.cpp` file? – Sam Varshavchik Jun 17 '21 at 03:21
  • 1
    This was my mistake. I was not compiling and linking `app1.cpp` and `sample1.cpp`. I changed the command to `g++ app1.cpp sample1.cpp -o app1` and changed `#include ` in `sample1.cpp` to `#include "sample1.h"`. The program works fine now! – Julian Jun 17 '21 at 03:32
  • 1
    The compiler is not going to look at `sample1.cpp` just because its name happens to be similar to something that exists in the text of `app1.cpp`. You need to tell the compiler to look at it. – n. m. could be an AI Jun 17 '21 at 08:51
  • 1
    "changed `#include ` You traded a mistake for a worse mistake. Don't do that. – n. m. could be an AI Jun 17 '21 at 08:54

1 Answers1

2

You have to compile all your .cpp files (sample1.h is included by preprocessor from information in app1.cpp only):

g++ app1.cpp sample1.cpp -o app1
Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28