2

I've written a bunch of code now, and sorted it in a fashion similar to this outline:

project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.

robrene
  • 359
  • 3
  • 14
  • how do you include, say bar.hpp from bar.cpp? – thbusch Jan 22 '11 at 14:27
  • @Sam: So far I'm only using `g++`, I'm currently reading up on Makefiles (using the GNU Make manuals) – robrene Jan 22 '11 at 14:46
  • @thbusch: I include bar.hpp from bar.cpp using `#include "bar/bar.hpp"`. I figured this should work since I tell the compiler about the include/ directory. – robrene Jan 22 '11 at 14:48

2 Answers2

4

I would recommend using some kind of build tool like CMake or Autotools. Creating your own Makefiles can be kind of a PITA to get right.

If you have a small directory structure with some C++ files which you want to quickly compile, you can do something like this:

find src/ -name "*.cpp" | xargs g++ -I include/
mtvec
  • 17,846
  • 5
  • 52
  • 83
  • Ah, this looks very much like something useful! However, I get a lot of linker errors with this about multiple definitions. Many of my headers have inline functions, and are included by multiple source files (directly or indirectly). How do I solve this? – robrene Jan 22 '11 at 15:16
  • @robrene You use guards in such situation. http://en.wikipedia.org/wiki/Include_guard – Haozhun Jan 22 '11 at 15:27
  • Hmmm, strange, this can't be the error, since I am using include guards. I was under the impression that they only protect per cpp file (so per object), and not when linking multiple objects together? I'm afraid that's not it... – robrene Jan 22 '11 at 15:37
  • @robrene: This looks more like you forgot to use the `inline` keyword. – mtvec Jan 22 '11 at 15:42
  • @Job: That was the problem! I thought the compiler would automatically inline the function seeing it was in a header file, I guess it only automatically inlines functions defined inside the class definition scope. Thanks! – robrene Jan 22 '11 at 16:06
1

I think the easiest approach is to use an IDE - for example NetBeans will generate Makefiles for you (other IDEs are available).

Community
  • 1
  • 1
John Carter
  • 53,924
  • 26
  • 111
  • 144