Question:
Including C++ header and cpp files?
?
2011-02-16 13:58:39 UTC
This is how I do it:
//file: my.h
#ifndef MY_H
#define MY_H

//class definition goes here

#include "my.cpp"
#endif

//file: my.cpp
#ifdef MY_H
#ifndef MY_CPP
#define MY_CPP

//Class implementation goes here

#endif
#endif

Is it OK to do it? I usually find it done the other way -- the CPP includes the H, but then you need to somehow tie all the CPP files together which is inconvenient. My method lets me type:
g++ myapplication.cpp

But their way makes me type:
g++ myapplication.cpp my.cpp

So am I missing something here? Or did I make some sort of breakthrough (not!)?
Three answers:
Cubbi
2011-02-16 14:03:15 UTC
The reason cpp files are usually separate is that later, when you have to make a change to my.cpp but *not* to myapplication.cpp, you would be able to avoid having to compile myapplication.cpp. You would only have to compile my.cpp

$ g++ -c my.cpp -o my.o

and link the binary

$ g++ -o myapplication myapplication.o my.o



If you #include all your source files into a single translation unit, you will have to recompile the entire source code after any small change to any file (which could be OK in your case, but a bad habit to pick up if you plan to work on larger software projects)



PS. I looked it up for you, turns out this practice is called "Unity build" and is actually used in some companies, especially for the builds you don't have to iterate (make small changes to). Nice, I learned something new too.
jplatt39
2011-02-16 14:13:39 UTC
You do NOT #include .cpp files in your header files. You LINK to object files compiled from them at run-time. Or you do something like:



g++ -o convert main.cpp fahrtocels.cpp celstofahr.cpp



which compiles them and links them together.



Or you compile them to object files and link them into libraries which you can link them to. Since I don't know what platform you are using (I use Linux) I suggest you look up dll files for windows, .so files in Linux/Unix. This is a page which covers them for Macs:



http://lists.apple.com/archives/unix-porting/2007/Dec/msg00006.html
decarlo
2016-12-01 04:18:00 UTC
you are going to be able to desire to have the #contain"worker.h> record in the C++ record with the main advantageous function after which you will declare the class worker #contain string #contain iostream #contain iomanip #contain "worker.h" utilising namespace std; int substantial() {worker Mydata; Mydata.getData(.......); Mydata.givepay(.....); Mydata.totalinfo(......); }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...