Here's the situation: I have three files, Test1.cpp and Test2.cpp. Test1.cpp can be compiled as-is into a stand-alone application. Test1.cpp also contains some functions that I would like to re-use in Test2.cpp. I'm using an #ifndef #endif block to conditionally exclude the main function of Test1.cpp so that when I compile Test2.cpp, the main function in Test2.cpp will be able to call functions defined in Test1.cpp. Example code:
--------------------------------------------
//File: Test1.h
#include <iostream>
void do_something();
--------------------------------------------
//File: Test1.cpp
#include "Test1.h"
void do_something();
{
std::cout<<"Done"<<std::endl;
}
#ifndef FN_MAIN
int main()
{
do_something();
return 0;
}
#endif
--------------------------------------
//File: Test2.cpp
#define FN_MAIN
#include "Test1.h"
int main()
{
do_something();
return 0;
}
--------------------------------------
Calling g++ with Test1.cpp works fine and behaves as expected, but calling g++ with Test2.cpp and Test1.cpp fails because main gets defined multiple times. However, calling g++ with -DFN_MAIN and the two source files fixes this problem. Is there any way to get around this? I'm thinking that this problem is coming from my less-than-complete understanding of the C++ preprocessor.
Note: My motivation for doing this is to reduce the size of the code on the project that I'm working on. The actual project includes both a stand-alone version of Test1.cpp and several other programs that use functions from Test1.cpp.