+ 1

Problem when including hpp & cpp files

Hi everyone! I'm having some trouble including header and source files in c++. Let's say I have these files (in the same folder): // foo.hpp #pragma once #include <iostream> void bar(void); // foo.cpp #include "foo.hpp" void bar(void) { std::cout << "bar"; } // test.cpp #include "foo.hpp" int main() { bar(); return 0; } When I compile with "g++ -Wall -Wextra test.cpp" it gives me the error "undefined reference to `bar()'" which seems to me that the compiler doesn't include the foo.cpp file... Where am I wrong?

23rd May 2021, 8:23 AM
Daniele
Daniele - avatar
8 Respostas
+ 3
You need to give both files as argument to g++ ``` g++ -Wall -Wextra test.cpp foo.cpp ``` source: http://www.math.uaa.alaska.edu/~afkjm/csce211/handouts/SeparateCompilation.pdf
23rd May 2021, 8:38 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
Daniele , right. Not sure if you noticed, but I have edited my answer to provide source from where I got answer. That text also mentions about makefiles. Using makefiles can be helpful if you have large project with many source files.
23rd May 2021, 8:46 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Thank you Martin Taylor ! Yeah, I've read a little about makefile (which I didn't know until this morning) and it's a very handy tool to use Which build system would you suggest on Windows?
23rd May 2021, 5:44 PM
Daniele
Daniele - avatar
0
Thank you so much 🇮🇳Omkar🕉 , I didn't know you have to do that 😅 So for every source file I include, I have to tell the compiler where to find it, is that right?
23rd May 2021, 8:41 AM
Daniele
Daniele - avatar
0
That's really helpful, thank you 🇮🇳Omkar🕉 !
23rd May 2021, 9:10 AM
Daniele
Daniele - avatar
0
At the moment I'm using VS Code as my main editor, so I might try GNU make On the other hand I was planning to download Visual Studio some day, so I may also download it directly! Anyway, thank you so much for these infos Martin Taylor !
24th May 2021, 2:24 PM
Daniele
Daniele - avatar