Reputation: 1261
I have several .cpp files that each are compiled separately into their own executables, I also want to use the functions in each of them with .h in a main executable. How do I go about doing this?
makefile
all: A B C
g++ -o main.exe -std=c++11 A.cpp B.cpp C.cpp
A: A.cpp
g++ -o A.exe -std=c++11 A.cpp
B: B.cpp
g++ -o B.exe -std=c++11 B.cpp
C: C.cpp
g++ -o C.exe -std=c++11 C.cpp
Upvotes: 0
Views: 128
Reputation: 98516
A C program cannot have two functions with the same name, main
is not special in that.
My advice is to separate the main
functions to their own CPP files and leave only the utility reusable functions in the common files:
all: A B C
g++ -o main.exe -std=c++11 all_main.cpp A.cpp B.cpp C.cpp
A: A.cpp
g++ -o A.exe -std=c++11 A_main.cpp A.cpp
B: B.cpp
g++ -o B.exe -std=c++11 B_main.cpp B.cpp
C: C.cpp
g++ -o C.exe -std=c++11 C_main.cpp C.cpp
An alternative would be to use conditional compilation to skip the undesired main
definitions. But that would be quite messy.
Something like:
void funA()
{ /*...*/ }
#ifdef A_EXE
int main()
{
}
#endif
And then in the makefile
:
A: A.cpp
g++ -o A.exe -std=c++11 -DA_EXE A.cpp
This use of conditional compilation trick, although a bit hacky and not very extensible, is used some times to provide a small test case or sample program within the code of a library.
Upvotes: 2
Reputation: 17455
Well, if main()
in each of A.cpp
, B.cpp
, C.cpp
is absolutely necessary, then you can put it under #ifdef
:
#ifdef STANDALONE_APP
int main(....) { ... }
#endif
and then pass -DSTANDALONE_APP
for each of A
, B
, C
...
Or maybe better use the advice of @rodrigo.
Upvotes: 1