Error compiling multiple files in C

I tried to compile two source files in Visual Studio 2010 (client.c and server.c).

I created a project and saved them in the "source files" folder, but when I ran, I got an error that is main()

already defined in another file. When I delete one file (either server.c or client.c), then the other file is compiled.

I tried a lot to fix everything and the same thing happened in the code blocks too.

+3


source to share


4 answers


As you mentioned, you have two C programs: server and client, I really assume that they will run as two different processes (or threads).

  • ( ). ( ) .
  • .

main()

- , main()

, . (, , main()

) , , , , main()

.
- , Reset / StartUp.


Additional data (not very relevant to this question):



In fact, if you try to declare two functions like below,

void customDestructor(void) __attribute__ ((destructor));

      

and

void customConstructor(void) __attribute__ ((constructor));

      

you can add any implementation you need before getting main()

executed.

+2


source


TL; DR . One binary (program) can contain one main()

. Multiple files, each containing main()

, should be treated as a separate peroject and not as one.

One binary can only contain one main()

. This is the point from which the binary is launched.



If you have a function in your source files main()

(which is quite likely), you cannot link the compiled object files into the same binary. You must create two separate binaries. You cannot link two separate object files that have an instance main()

defined in them.

I'm not very familiar with VS, but you might find some options to create two separate binaries from two different source files if possible.

0


source


They seem to be telling Visual Studio that these two files should be used to compile the same target. When you tell the compiler, one and only one of the files in the project should have a function main

.

You need to define two separate goals. To be honest, I don't use VS for this kind of thing; I would use a simple Makefile that would easily resolve two separate targets in the same Makefile.

0


source


Only one feature allowed main

.

According to your detail, both files c

can contain functions main

. Then your compiler generates an error.

0


source







All Articles