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:
#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
?
CodePudding user response:
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