You can have more than one main in the same project, if to each main will correspond a different executable in the build directory tree.
The following example is using CMake, I don't know if it can be done with other build-process manager software.
Store the following two .cpp files in a folder called source, and name them square_root.cpp, and power_of_two.cpp:
square_root.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
if (argc < 2) {
fprintf(stdout,"Usage: %s number\n",argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
double outputValue = sqrt(inputValue);
fprintf(stdout,"The square root of %g is %g\n",
inputValue, outputValue);
return 0;
}
power_of_two.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
if (argc < 2) {
fprintf(stdout,"Usage: %s number\n",argv[0]);
return 1;
}
double inputValue = atof(argv[1]);
double outputValue = inputValue*inputValue;
fprintf(stdout,"The power of two of %g is %g\n",
inputValue, outputValue);
return 0;
}
Note that they both contains a method main.
Then, in the same folder, add a .txt called CmakeLists.txt: it will tell the compiler the number of executable, how to call them and where to find the main(s).
CmakeLists.txt:
cmake_minimum_required (VERSION 2.6)
project (Square_and_Power)
add_executable(Square2 square_root.cpp)
add_executable(Power2 power_of_two.cpp)
Create a new folder called build in the same root of the source, and then use cmake to coufigure and generate. Take a look at the structure of folder created into the folder build.
Open a terminal in the build and type make.
→ make
[ 50%] Built target Power2
Scanning dependencies of target Square2
[ 75%] Building CXX object CMakeFiles/Square2.dir/square_root.cpp.o
[100%] Linking CXX executable Square2
[100%] Built target Square2
If no errors occur you will have two executables: Square2 and Power2.
→ ./Square2 5
The square root of 5 is 2.23607
→ ./Power2 5
The power of two of 5 is 25
So you have the same project with two mains that compiled two different applications. The two cpp files can then share the same header and additional methods in other .cpp or .h files in the project.
I suggest to take a look as well at the cmake tutorial https://cmake.org/cmake-tutorial/
There may be other methods to have similar if not the same results but I do not know any. Hope other user will contribute to this thread!