Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – Compile and link multiple files

I have a project with the following structure:

Item.cpp
Item.h
main.cpp
Makefile

The following source code is in the Item.h file:

class Item {
    public:
        Item();
        ~Item();
};

The following source code is in the Item.cpp file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Item::Item() {
    std::cout << "Item created..." << std::endl;
}

Item::~Item() {
    std::cout << "Item destroyed..." << std::endl;
}

The following source code is the content of the main.cpp file:

#include "Item.h"

#include <iostream>


int main() {
    std::cout << "Initialize program..." << std::endl;
    Item item_1();
    std::cout << "Hello world!" << std::endl;

    return 0;
}

And finally, the following source code is the Makefile file:

CXX = g++

all: main item
    $(CXX) -o sales.o main.o Item.o

main:
    $(CXX) -c main.cpp

item:
    $(CXX) -c Item.cpp

clean:
    rm -rf *.o

When I run the make command and then I run the compiled code with the command ./sales.o, I get the following output:

Initialize program...
Hello world!

Why is the output of the constructor method of the class Item not printed in the console? I found in some web pages that you can compile the source codes in steps and then you can link it with the -o option when using g++ but it does not work in this case. How can I compile this source codes step by step and then link it in the Makefile?

>Solution :

I’m surely you ignored this warning :

warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]

#include "Item.h"

#include <iostream>


int main() {
    std::cout << "Initialize program..." << std::endl;
    Item item_1;
    std::cout << "Hello world!" << std::endl;

    return 0;
}

just remove parentheses it will be work
test : https://godbolt.org/z/KrdrhvsrW

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading