简体   繁体   中英

How to compile a C project with more than one main function?

I am new to C, and now read some textbook and going to apply its examples.

The problem is, whenever I creates a new project and try to put more than one file that contains a main function, the linker (as I thougt0 explains saying:

/home/mohammed/tmp/abcd/main.c:4: multiple definition of `main'

(BTW, I used many IDEs, MonoDevelop, QT creator, VS2010, Codebloks, ...) I am currently uses QT Creator, It seems to be a very nice IDE.

So, there's not a workaround to solve such problem??

EDIT:

I am asking because I am in the learning stage, and not do real programming right now. I just need a simple way to create programs in C without have to create a separate project per book example. At the same time, I don't want to use Gedit/VI + commandline.

So, Isn't there any way such as cleaning the project, then compile the - just - one file that I need to run ??? BTW, In JAVA we can run a program that cotains more than one main (the IDE give me the choice among them)

What are you trying to do with the multiple main functions?

If you are trying to compile multiple different programs at once, you need to compile each one separately (ie only one main per program).

If you are trying to compile one program and want the multiple main functions all to run, you can't. You need to specify only one main and rename the others to something else (and call them from the single main in the order you want them to run).

If you are trying to use just one of the main functions as the single entry point to your program and ignore the others, then you should not include the files with the other main s when you are linking. I suggest placing each main in a separate file if you wish to keep them, and only include one of these main-files when you link/compile.

If you get this error by mistake, then you are probably doing something wrong with the project in your IDE. Perhaps you are accidentally trying to compile multiple different programs into one? You might need to specify each file containing a main as a separate build product. C is not like Java where you can put a main method inside every class and specify which one to call; the main in C is a global name.

You can't possibly have more than one entry points in your application. When the final executable is started, the entry point function (main) is called. And this one can't be ambiguous.

So if you wanted to call them one by one you could chain them like this:

void main1() {} /* Note that these aren't called main. */
void main2() {}
...

int main(int argc, char* argv[]) {
    main1();
    main2();
    return 0;
}

You could even call them using threads (eg boost.Thread), so that they run parallel. But you can't have multiple functions named main linked together.

If you instead want them to be separate programs each, you will have to link them separately.

Each program must have exactly one main function. However, main can call any function you want (including itself, though this can be confusing). Thus, you should break the program up into logical parts.

As many have said, you can only have one main per program. You don't want to go through the hassle of creating a new project for each example as you go through a book. That's understandable, but you'll have to do basically that. I see two alternatives:

  1. Use the new project function in your IDE (like VS2010). This will do all the hard work for you. You can always delete them later.
  2. If you don't care to keep the code around, just empty the file (or even the main() function) and re-use it. With book examples, you probably will never revisit the code anyway so just deleting it should be fine.

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!

Actually, I find Dev-C++ supports working on multiple main files that are not part of any project, so I can create an run as many files as I need.

Thanks all who corporate here :) Gook luck for all.

Also, for Linux/win I found Code::Blocks do that trick. thanks.

Well i think that QtCreator is a great IDE.

For learning and testing out it would be nice to be able to have multiple mains for ease of use, however as explained before you can only have one main because thats the way a project is defined in QTcreator / .pro qmake files.

You could create multiple targets in pro or make / CMAKE files.

But for testing i did this in the .pro file for the project.


MAIN = simpletree_test.c

SOURCES += \
    $$MAIN \
    simpletree.c \
    graph_tree.c \
    redblacktreenode.c \
    redblacktree.c \
    redblack.c \
    pointers.c

HEADERS += \
    simpletree.h \
    graph_tree.h \
    redblacktreenode.h \
    redblacktree.h \
    redblack.h \
    pointer_manipulator.h

message("The project contains the following files:")
message($$SOURCES)

So i just exchange the main file name in the variable called MAIN in the pro file. the use it in the SOURCES variable.

As you can see i test several implementations of trees. Right now testing a simple variation of trees where i test out new implementation for finding a specific node, before testing them on the balanced tree.

The method is however not perfect, since you cannot have same names for functions etc. And after a while i can be tough to come up with new names for find_node() or traverse_tree()

In QtCreator, you can right click a file and select the "Compile" option, which compiles only the selected file, and the required dependencies. So if you compile one of your main files like that and that file doesn't include any other main file, this should work.

I'm guessing one of your IDEs automatically creates a file with a main function. Check around to see if one has already been created.

You cannot have multiple definitions of main. The "main" function is what, in essence, defines what your program does. If you had more than one copy of main, which one would you expect to be executed?

The solution to your problem is to use libraries; if you want to reuse functionality, then you should create a library, which is basically identical to a program except that while it has functions and data (like a program), it doesn't have a special function called "main", and hence has no "entry point" where execution should begin when it would be double-clicked or otherwise loaded by the OS. Libraries come in two variants: shared/dynamic and static. Either one should do. Each program that you create will have its own main function, but you can reuse your library without any problems in different programs.

Now as to the practical element of creating a library... see my C++ Library Project Template .

As others have said, your project may only have a single main function.

Why are you trying to have more than one main function? Is it because you are putting multiple small example programs into one project and each of these has a main? If that is the case you may need to create a separate project for each example so that your IDE won't ask the compiler to compile/link source from multiple examples into one program. Your IDE might also support a concept like a target, that allows you to keep code for multiple, related programs in one project and than choose which program (target) to actually build. The IDE will then compile/link only the files in that target.

try using static keyword eg:

file1.cpp:

#ifdef RUN_FILE1
#define STATIC static
#else
#define STATIC
#endif

int STATIC main(int argc, char **argv(){}

file2.cpp:

#ifdef RUN_FILE2
#define STATIC static
#else
#define STATIC
#endif

int STATIC main(int argc, char **argv(){}

for compilation add /DRUN_FILE2 or /DRUN_FILE1 .

Just an idea.

IF you're using MS linker, use the /FORCE:MULTIPLE linker option. The first main symbol encountered will win. Not sure what the option is for other linkers.

The best solution I could find was on Eclipse creating projects every time to run a single file? it has some alternatives than creating a new project for each program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM