Visual Studio: how to create a project that would compile 2 exe files? - c++

So I have main.cpp and main2.cpp with int main in each. I want to get 2 exes out of it. Is it possible and what would be instruction to create such project?

Nope, Visual Studio's project model is rigidly built around the assumption that "one project generates one output".
If you need two executables, you have to create two projects. You can keep them in the same solution to make things easier for yourself, but they have to be separate projects.
Edit
Ok, as other answers have pointed out, it can of course be done, if you're desperate. You can add a custom build step, which does anything you like, including building another executable. (However, the build system won't understand that this file should be considered project output, and so some scenarios may fail: for example the file won't be automatically copied to the output folder, and when checking dependencies before a rebuild, it might not be able to understand which files to check, and what (or how) to rebuild.)
Visual Studio (at least up to 2008, not sure about 2010) also allows the use of nmake files, but then I think you're stretching the definition of "a Visual Studio project".
But under "normal" circumstances, one project implies one output. And in order to get two executables, you'd normally create two projects.

You need a solution which includes two projects. Have a read of the Visual Studio documentation on solutions and projects.

Here's my solution, since nobody in a Google search seems to suggest this method. It's quite simple and I've used/seen it used in other IDEs (like Code::Blocks).
Within your project, create a configuration for each output that you want. Then, only include one main source file in each configuration.
In VS, this means for each source file with main: right-click -> Properties -> Excluded From Build = Yes. So, once you're done, only one main source is built for each configuration. You can then specify a different output for each configuration in the Project Properties. I did this on VS 2010, but it should probably work with other versions.
I'm using this approach so that I can have several tests for one project, without cluttering the solution with more test projects than actual code projects.

I don't know if it can be done ,but the only change you have ,to do this ,is with custom build step.
EDIT: Since someone downvoted this ,i did a test making a dummy configuration.
In the custom build step I two Link-cmds (copied form original link-cmdline and modified it a bit) taking as input main1.obj resp. main2.obj and outputting App1.exe resp. App2.exe.
It's executed after Compiling and before linking.
It worked !
The downside is I cannot prevent (yet) the linking ot the orinal exe (which errors on duplicate main function).
Solution to this could be to have a lib project excluding the sources with main()from build and build them in the custum-step too.
So the answer to the question should : Yes ,it can be done!

You can't have more than one main() function in a single visual studio project. So you can't compile 2 executables, the only way is to make two different project in the same solution

You can create a solution with two project one for each output you want. Then head to Build menu and select Batch Build.. and select both projects.
If you want both exe files to be in one place you can specify a custom Post-build action:
For both project:
view the project properties page and in Build events select Post-Build events, then in the Command line field enter the command that will copy the output to the location you want, something like:
copy $(TargetPath) c:\yourlocation /Y
Then after you build the solution the output files will be copied to that location.

Another option you have is to use conditional compilation with sth like
main()
{
#ifdef VERSION1
call_main_logic();
#else
call_main2_logic();
#endif
}
and then define different configurations within the project. For each configuration you will then need to define preprocessor symbols appropriately (in: project settings -> configuration properties -> C/C++ -> preprocessor).
Please note, that it will be only one executable created at a time, but with switching configurations you'll get the one that does what you want at the moment.
... which may suit your needs or not, depending on more specific situation that you are in.
Edit: In addition, since different configurations create their separate output folders, you will have your both execs as outputs.

Related

In Visual Studio, I don't want to commit my Debug folder, but it has the dll file in it, and if I move it project won't compile

What should I do?
Basically, I want to commit my Visual Studio 2012 project, but it has a Debug folder in it that we traditionally don't commit. Only problem is that the Debug folder has the project's dll in it, and if I move the dll to the folder's parent, the project no longer compiles.
So here's the structure:
Project Folder > MSVC_2012 > Debug folder, sln file, etc.
And in that Debug folder is the dll. How do I move that out of the Debug folder into MSVC_2012?
Your question isn't entirely clear on details, but here are some options (and ways you could improve the question):
Your question looks like an XY problem. You stated that "if I move the dll to the folder's parent, the project no longer compiles." in which case the real problem here is why it isn't compiling. We'd need more details to figure out why. You also need to be clearer what you mean by "if I move the dll" - you can't "move" a DLL before it is compiled, and if you move it afterwards, then by definition the compiling worked, so actually your statement as it stands doesn't make sense. In any case, you should probably focus on fixing your broken build rather than fiddling with it to meet the needs of your version controlling.
You haven't specified why it is a problem for the DLL file to be in the Debug folder. I assume it's because you want to commit it to your VCS (which you didn't explicitly state as your goal). In which case, are you aware that it is not normal practice to commit the binary output of your code? So one solution might be to reconsider why you are trying to commit the DLL in the first place.
You didn't specify which VCS you're using. In Git (and I assume in most other VCS') you can have finer grain control over what to exclude from commits than whole folders. So, another option is to configure your VCS to ignore the Debug folder with the exception of any DLL files contained inside it.
You can change where MSVC places your DLL file in the project property pages under Configuration Properties -> General -> Output Directory. Presumably this is what you meant when you referred to "moving" the DLL?
Finally, as per other people's comments on your question, if you want the DLL to be in both places you can use a post-build step to copy it to the relevant place. To achieve this go to the project property pages under Configuration Properties -> Build Events -> Post-Build Event then enter the relevant command (the same as you would type at a command prompt) to do the copying e.g. copy myfile.dll .., or as Alex Farber suggests, use VS macros to specify the locations in a more generalised way. See this page for a list of available macros that you can insert into the command. This should be considered a last resort solution for two reasons - (a) it is a hack, as you are redundantly copying a binary output to circumvent a shortcoming in your version controlling and/or build, when you should fix the problem at root, and (b) build events have a serious flaw in them in Visual Studio and that is that they don't allow values to be inherited. This makes them a maintenance nightmare in bigger projects.

Multiple main CPP files in VisualStudio?

I have a sample directory of some software, which contains multiple files with multiple main functions. May I assemble all of these files into single project, compile them and then run specific ones without getting main already defined error? Suppose I don't want to create separate project for each cpp file.
UPDATE
I need simple one-two-click solution (if it exists). I don't want to distribute files among folders or refactor files content. For example in Eclipse/Java you can right-click any file with main and run it. And there can be many of main files in one project. Is this possible for VisualStudio/CPP?
UPDATE 2
I know that C++ is not Java and that Visual Studio is not Eclipse. My question is about automation of some manual operations.
Put those main functions in separate namespaces and then define, which one do you want to run, eg.
File1.cpp
namespace F1
{
int main(int argc, char * argv[])
{
// ...
}
}
The-real-main.cpp
int main(int argc, char * argv[])
{
if (whatever)
return F1::main(argc, argv);
}
Edit: In response to additional information.
C++ is not Java and VS is not Eclipse :) The natural way to maintain multiple programs at once in VS is to put multiple projects (one for each executable or library) in a single solution. If you want to run a project, simply right-click it in Solution Explorer, select Set as Startup Project, and then click the Start button to run it.
To add a project to solution, right-click the solution and choose Add | New project... or Add | Existing project.
In Visual studio:
Create one "Solution" - under the solution one can create multiple "projects". Each project will compile separately into an executable. Compiling is done as normal other than "unloading" the unneeded projects. In order to reopen one of the other projects simply choose "reload project" from the solutions explorer.
This function is useful for study/organizational purposes where one is grouping source files in a common "folder" for easy search and access while still compiling/debugging separately. The main advantage from what I can tell is that one can easily navigate ones projects using the solution explorer.
I haven't worked OpenCV, but it uses cmake, and has a CMakeLists.txt in the sample directory. There's some discussion about building the samples using cmake here.
Cmake doesn't build anything itself, it generates build scripts for the target platform, and should be able to create Solution and Project files that you can load into Visual Studio.
May be the most simple solution is to use multiple build configurations. Just create a number of build configurations define an entry point for each of them.
In Visual Studio, you must create one project per executable you want to create.
If only one file needs to be built, you can use 'Exclude Files From Build' option in Properties to exclude the rest. Select multiple source files and exclude them at once. Obviously, this solution does not work if you are accessing functions/symbols across files.
Yes, there is a simple way to do this:
Right click these source files which contain a main function and you don't want to run in the solution explorer window, then go to property->configuration->general->excluded from build, select yes.
So these source files won't compile and run when you build and run the project. When you want to run another source file just include it and exclude other source files.
Just a few basic steps to compile & run multiple main files in each c++ project:
Suppose you have c1.cpp, c2.cpp ... c100.cpp files.
Click on Show all files
Exclude all the cpp files except the one you want to compile and run.
So in each instances you project only have one main file but you can see all the files under project. So each time you want to run any file just exclude other files and include this file only.

How to create two mains in an eclipse C++ project

We've got a program which runs separately, executed with an execvp command. So it needs a main method, but I believe that poses a problem to eclipse with a managed make. Do we have to keep this code segregated into a separate project, or is there a way to incorporate it into the same eclipse project?
Create a project for each executable that has a main() function, and create an additional project to represent the software as a whole (a "container" project of sorts). Eclipse allows you to specify projects as dependencies of other projects, and in this case you will want to set up the container project to list the other projects as "Referenced Projects".
To do this, create the container project, then right-click on the project in the left-hand column (project explorer) and click "Properties". A dialog box will appear. Select the "Project References" item in the list on the left-hand side and you will see a list of all projects that Eclipse is currently working with. Check the boxes next to the projects for your individual executables, then click OK. Now, when you perform a build on the container project, Eclipse should automatically perform a build on these dependent projects as well.
When using sub-projects in this manner, I have (personally) found it useful to create a working set that includes the container project and all of the sub-projects (this can make searching the entire software project easier).
Keep it in the same project and use preprocessor defines which you define differently depending on what kind of main you want to include in the current project. Here the mains are in the same file, but they can of course reside in different files.
#if defined(MAIN_ONE)
int main()
{
// Do stuff
}
#elif defined(MAIN_TWO)
int main()
{
// Do some other stuff
}
#endif
If the makefile being invoked doesn't compile the 2 main() methods into the same executable, it won't cause a problem. I don't know how eclipse projects are handled - if it's like VS, where "project" means a single executable or library, and "solution" is a group of "projects", then it would seem you'd need more than one project. If, OTOH, a "project" can contain different "subprojects" where a "subproject" is an executable or library, you should be able to handle that easily.
I am not aware of any easy way to build two mains using Eclipse build system. The smallest change you need to do might be to move to makefiles and use makefile targets to build.
Instead, I'd advise you to move to using CMake. CMake can be used to generate makefiles to be used with eclipse. The advantage you get from using CMake is that you can easily state how to build the libraries and link the libraries to form the executables. CMake can generate builds for Eclipse, Visual Studio, Code Blocks, or makefiles (so you can use command prompt).
This is built in the C++ language. You would have to modify it to get your result. There is something to do 2 things at once if that is what you want.

Building both DLL and static libs from the same project

I have a number of native C++ libraries (Win32, without MFC) compiling under Visual Studio 2005, and used in a number of solutions.
I'd like to be able to choose to compile and link them as either static libraries or DLLs, depending on the needs of the particular solution in which I'm using them.
What's the best way to do this? I've considered these approaches:
1. Multiple project files
Example: "foo_static.vcproj" vs "foo_dll.vcproj"
Pro: easy to generate for new libraries, not too much manual vcproj munging.
Con: settings, file lists, etc. in two places get out of sync too easily.
2. Single project file, multiple configurations
Example: "Debug | Win32" vs "Debug DLL | Win32", etc.
Pro: file lists are easier to keep in sync; compilation options are somewhat easier to keep in sync
Con: I build for both Win32 and Smart Device targets, so I already have multiple configurations; I don't want to make my combinatorial explosion worse ("Static library for FooPhone | WinMobile 6", "Dynamic library for FooPhone | WinMobile 6", "Static library for BarPda | WinMobile 6", etc.
Worse Con: VS 2005 has a bad habit of assuming that if you have a configuration defined for platform "Foo", then you really need it for all other platforms in your solution, and haphazardly inserts all permutations of configuration/platform configurations all over the affected vcproj files, whether valid or not. (Bug filed with MS; closed as WONTFIX.)
3. Single project file, selecting static or dynamic via vsprops files
Example: store the appropriate vcproj fragments in property sheet files, then apply the "FooApp Static Library" property sheet to config/platform combinations when you want static libs, and apply the "FooApp DLL" property sheet when you want DLLs.
Pros: This is what I really want to do!
Cons: It doesn't seem possible. It seems that the .vcproj attribute that switches between static and dynamic libraries (the ConfigurationType attribute of the Configuration element) isn't overrideable by the .vsprops file. Microsoft's published schema for these files lists only <Tool> and <UserMacro> elements.
EDIT: In case someone suggests it, I've also tried a more "clever" version of #3, in which I define a .vsprops containing a UserMacro called "ModuleConfigurationType" with a value of either "2" (DLL) or "4" (static library), and changed the configuration in the .vcproj to have ConfigurationType="$(ModuleConfigurationType)". Visual Studio silently and without warning removes the attribute and replaces it with ConfigurationType="1". So helpful!
Am I missing a better solution?
I may have missed something, but why can't you define the DLL project with no files, and just have it link the lib created by the other project?
And, with respect to settings, you can factor them out in vsprop files...
There is an easy way to create both static and dll lib versions in one project.
Create your dll project. Then do the following to it:
Simply create an nmake makefile or .bat file that runs the lib tool.
Basically, this is just this:
lib /NOLOGO /OUT:<your_lib_pathname> #<<
<list_all_of_your_obj_paths_here>
<<
Then, in your project, add a Post Build Event where the command just runs the .bat file (or nmake or perl). Then, you will always get both a dll and a static lib.
I'll refrain from denigrating visual studio for not allowing the tool for this to exist in a project just before Linker (in the tool flow).
I think the typical way this is done is choice 2 above. It is what I use and what I have seen done by a number of libraries and companies.
If you find it does not work for you then by all means use something else.
Good luck.
I prefer 2 configurations way.
Setup all common settings via 'All configurations' item in a project properties windows. After it separated settings. And it's done. Let's go coding.
Also there is very good feature named 'Batch build', which builds specified configurations by turn.
Multiple projects are the best way to go - this is the configuration i have most widely seen in umpteen no of projects that i have come across.
That said, it might be also possible to implement the third option by modifying your vcproj files on the fly from external tools(like a custom vbscript), that you could invoke from a make file. You can use shell variables to control the behavior of the tool.
Note that you should still use use visual studio to make the build, the makefile should only launch your external tool if required to make the mods and then follow that by the actual build command
I use Visual Studio 6.0 (Still) due to issues that are preventing us from Migrating to VS2005 or newer. Rebuilding causes severe issues (everything breaks)... so many of us are considering lobbying a migration to GnuC++ moving forward in a structured way to eventually get us off of licensed Visual Studio products and onto Eclipse and Linux.
In Unix/Linux it is easy to build for all configurations.. so I can't believe what a time and productivity sink it is to try and accomplish the same task in Visual Studio. For VS6.0 I have so far found that only having two separate projects seems to be workable. I haven't yet tried the multiple configuration technique, but will see if it works in the older VS6.0.
Why not go for version 1 and generate the second set of project files from the first using a script or something. That way you know that the differences are JUST the pieces required to build a dll or static lib.

Complex builds in Visual Studio

I have a few things that I cannot find a good way to perform in Visual Studio:
Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it does not work if I don't know names and/or the number of auto-generated source files. I can easily solve it in GNU make using $(wildcard generated/*.c). How can I do something similar with Visual Studio?
Can I prevent pre-build/post-build event running if the files do not need to be modified ("make" behaviour)? The current workaround is to write a wrapper script that will check timestamps for me, which works, but is a bit clunky.
What is a good way to locate external libraries and headers installed outside of VS? In *nix case, they would normally be installed in the system paths, or located with autoconf. I suppose I can specify paths with user-defined macros in project settings, but where is a good place to put these macros so they can be easily found and adjusted?
Just to be clear, I am aware that better Windows build systems exist (CMake, SCons), but they usually generate VS project files themselves, and I need to integrate this project into existing VS build system, so it is desirable that I have just plain VS project files, not generated ones.
If you need make behavior and are used to it, you can create visual studio makefile projects and include them in your project.
If you want less clunky, you can write visual studio macros and custom build events and tie them to specific build callbacks / hooks.
You can try something like workspacewhiz which will let you setup environment variables for your project, in a file format that can be checked in. Then users can alter them locally.
I've gone through this exact problem and I did get it working using Custom Build Rules.
But it was always a pain and worked poorly. I abandoned visual studio and went with a Makefile system using cygwin. Much better now.
cl.exe is the name of the VS compiler.
Update: I recently switched to using cmake, which comes with its own problems, and cmake can generate a visual studio solution. This seems to work well.
Specifically for #3, I use property pages to designate 3rd party library location settings (include paths, link paths, etc.). You can use User Macros from a parent or higher level property sheet to designate the starting point for the libraries themselves (if they are in a common root location), and then define individual sheets for each library using the base path macro. It's not automatic, but it is easy to maintain, and every developer can have a different root directory if necessary (it is in our environment).
One downside of this approach is that the include paths constructed this way are not included in the search paths for Visual Studio (unless you duplicate the definitions in the Projects and Directories settings for VS). I spoke to some MS people at PDC08 about getting this fixed for VS2010, and improving the interface in general, but no solid promises from them.
(1). I don't know a simple answer to this, but there are workarounds:
1a. If content of generated files does not clash (i.e. there is no common static identifiers etc.), you can add to the project a single file, such as AllGeneratedFiles.c, and modify your generator to append a #include "generated/file.c" to this file when it produces generated/file.c.
1b. Or you can create a separate makefile-based project for generated files and build them using nmake.
(2). Use a custom build rule instead of post-build event. You can add a custom build rule by right-clicking on the project name in the Solution Explorer and selecting Custom Build Rules.
(3). There is no standard way of doing this; it has to be defined on a per-project basis. One approach is to use environment variables to locate external dependencies. You can then use those environment variables in project properties. Add a readme.txt describing required tools and libraries and corresponding environment variables which the user has to set, and it should be easy enough for anyone to set up.
Depending on exactly what you are trying to do, you can sometimes have some luck with using a custom build step and setting your dependencies properly. It may be helpful to put all the generated code into its own project and then have your main project depend on it.