241

I have two solutions which have some common code, so I'd like to extract it out and share it between them. Furthermore, I'd like to be able to release that library independently because it might be useful to others.

  • What's the best way to do it with Visual Studio 2008?
  • Is a project present in more than one solution?
  • Do I have a separate solution for the separate piece of code?
  • Can a solution depend on another one?
Winner Crespo
  • 1,394
  • 12
  • 29
pupeno
  • 256,034
  • 114
  • 324
  • 541
  • 16
    Its 2014. Nuget is the answer. – Ravi Dec 05 '14 at 21:52
  • 1
    @Ravi I wanted to modularize a Visual Studio Web Application developed at my office.However, when I try to think of modularizing the Visual Studio Web Application into different Web Applications, the circular dependency between components comes up which is Wrong.For example, I can't modularize the POCO project for each of the planned Web Application because there is too much dependency. Is there a way I could use Nuget to help with Modularizing? – CS Lewis Oct 29 '15 at 09:57

16 Answers16

254

You can "link" a code file between two projects. Right click your project, choose Add -> Existing item, and then click the down arrow next to the Add button:

Screengrab

In my experience linking is simpler than creating a library. Linked code results in a single executable with a single version.

Dan Atkinson
  • 10,801
  • 12
  • 78
  • 106
Andomar
  • 216,619
  • 41
  • 352
  • 379
  • 9
    Sweet - that's the answer I was looking for. I didn't want a collection of DLLs. cheers – CAD bloke Mar 10 '11 at 12:58
  • I use VS2010 and Windows 2003 and do not find Add button with down arrow. My open dialog has only Add button. Is this OS related feature? – Tomas Mar 15 '11 at 09:20
  • @Tomas: Works for me, same setup. Are you sure you're in the `Add -> Existing item` dialog? – Andomar Mar 15 '11 at 13:40
  • I'm also missing the "Add As Link" option on a Web Site project trying to add a class file from a WP7 project (VS2010) – dr3x Aug 02 '11 at 12:01
  • 66
    Why would you do it this way? This is why we have libraries, encapsulation. I see no business sense, or logical sense on why you'd do this. – Ryan Ternier Aug 23 '11 at 15:49
  • @Ryan Ternier: It requires an external dll. Andomar: Does the *link* fail when a developer on another machine tries to open the solution; they're not going to have the same hard-drive layout as i would. – Ian Boyd Sep 01 '11 at 18:51
  • 17
    Furthermore your links may not be under same source control. This is very dangerous suggestion. – Kugel Nov 21 '11 at 09:58
  • 11
    There are situations where this solution is useful. As an example I am developing in InfoPath 2007 where it is not straightforward to deploy a separate DLL into SharePoint. In order to share common functionality between InfoPath forms the linked class file approach is very useful. It is placed one level above the individual form projects and everything is source controlled at the root level. – Oliver Gray Sep 20 '12 at 17:50
  • 6
    As another example of usefulness say that you are developing two applications that need to communicate to each other. One is 64 bit and the other is 32 so you do not necessarily want separate dlls built from the same code to reference form each project. This way you can mimic the c functionality of using a .h file. – user912447 Apr 12 '13 at 17:05
  • 1
    @RyanTernier to share the `AssemblyFileVersion` across all projects in once solution while leaving the `AssemblyVersion` controlled by the projects themselfes (as they shouldn't be bumped without changes). Now the AssemblyFileVersion is the same across all assemblies of a certain build whithout the extra overhead maintaining x AssemblyInfo.cs for a simple bugfix release. See: http://blogs.msdn.com/b/jjameson/archive/2009/04/03/shared-assembly-info-in-visual-studio-projects.aspx – mbx Jul 09 '13 at 08:29
  • 2
    Another situation where this is useful: INTERFACE-defining source file defined in a server process, and used by a client process. Don't want two copies of that interface source file. – ToolmakerSteve Apr 26 '14 at 22:19
  • 1
    Re my previous comment: I just learned that it is possible to put the common interfaces into a third project, which does not implement the interfaces, so that the client and server projects can both access the interfaces. In my current situation, that seemed overkill, but its good to be aware of all options. http://stackoverflow.com/questions/1638240/interfaces-separated-from-the-class-implementation-in-separate-projects – ToolmakerSteve Apr 26 '14 at 22:54
  • 1
    Per MSDN (http://msdn.microsoft.com/en-us/library/jj169818.aspx) it appears Visual Studio 2013 has added a separate menu entry for adding a link. Instead of selecting **Add Existing Item**, choose **Link to Existing Item**. – Nick Sep 05 '14 at 23:01
  • This is by far the worst suggestion possible for using common code within your solution. It breaks the important feature of VS which is the refactor.. If the file is changed/renamed all links are broken. Imagine a huge solution where everything is pointing to this file and it the name changes. Good luck relinking the entire solution again! – nav Jul 27 '15 at 17:20
  • 5
    @nav: same is true when you reuse one DLL in two different solutions, if you refactor in one solution, the other solution will not get refactored. – Doc Brown Sep 11 '15 at 13:10
  • @DocBrown : Yes your point is good for a dll that is commonly used, but in my opinion, not a whole solution of class libraries. – nav Sep 11 '15 at 18:59
  • 1
    This should be the marked answer. I came from RealBasic and I was missing this. – beppe9000 Mar 04 '16 at 12:35
  • This is awful! Especially when working on a team environment and using version control software. – Leo May 12 '19 at 05:59
  • There is no such a button in VS2019 for a c++ project. – Oleksa Jul 31 '20 at 17:47
75

A project can be referenced by multiple solutions.

Put your library or core code into one project, then reference that project in both solutions.

pupeno
  • 256,034
  • 114
  • 324
  • 541
ilivewithian
  • 18,642
  • 19
  • 93
  • 158
  • 167
    OK but how? Some instructions? – cja Feb 05 '13 at 13:05
  • 2
    This (old) answer is incomplete by itself due to resulting in multiple assemblies: however, when *coupled* with ILMerge - especially with the internalize option - it becomes a very powerful solution. – user2246674 Jun 28 '13 at 05:27
  • 2
    @user2246674: why is it incomplete because of multiple assemblies? The OP said nothing about a single assembly. – John Saunders Feb 23 '14 at 01:17
  • How would this affect refactoring? If I rename a variable in the shared project, will all the solutions be updated, even the ones not opened? – Feng Jiang Sep 17 '14 at 02:48
  • 1
    @Jfly: Renaming things that are not publicly visible will not affect outside code. Renaming things that _are_ publicly visible should only be done where all the projects using the common code, and the common code itself, are in a single solution. You can manually create "master" solutions that contain all of these projects, and which are used only for this purpose. – John Saunders Oct 23 '14 at 17:37
  • With NuGet you can run into problems as the package location will change based on which solution gets opened first. This is especially painful on build servers when you're only building one solution but the other solutions package path gets checked in. – Shane Courtrille Apr 18 '16 at 17:45
  • When a project is referenced in multiple solutions does that solution contain a separate instance of the project or are they all referring to the same instance? In our case we have multiple solutions that refer to a "Core" project that contains a lot of mapping data that they all access at various points. Thanks! – Jeff L Feb 28 '18 at 18:21
  • 1
    It depends what you mean by another instance. You'd probably do well to start a new question with some more details. – ilivewithian Mar 01 '18 at 18:36
  • I linked a shared project between two solutions by creating it in one solution, and then adding it to the other solution with "add existing project". The project is not duplicated, it's just referenced, and the path is relative to the second solution's location (../../something/project.shproj). I am very impressed by how smart Visual Studio is – Sasinosoft Dec 17 '20 at 02:45
34

File > Add > Existing Project... will let you add projects to your current solution. Just adding this since none of the above posts point that out. This lets you include the same project in multiple solutions.

Aseem Kishore
  • 9,137
  • 8
  • 44
  • 55
25

You can include a project in more than one solution. I don't think a project has a concept of which solution it's part of. However, another alternative is to make the first solution build to some well-known place, and reference the compiled binaries. This has the disadvantage that you'll need to do a bit of work if you want to reference different versions based on whether you're building in release or debug configurations.

I don't believe you can make one solution actually depend on another, but you can perform your automated builds in an appropriate order via custom scripts. Basically treat your common library as if it were another third party dependency like NUnit etc.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • The project does have track where nuget packages are stored and this can be changed by solution opening which can lead to headaches at build time so this is a preferable solution. – Shane Courtrille Apr 18 '16 at 17:47
23

You can wild-card inline using the following technique (which is the way in which @Andomar's solution is saved in the .csproj)

<Compile Include="..\MySisterProject\**\*.cs">
  <Link>_Inlined\MySisterProject\%(RecursiveDir)%(Filename)%(Extension)</Link>
</Compile>

Put in:

    <Visible>false</Visible>

If you want to hide the files and/or prevent the wild-card include being expanded if you add or remove an item from a 'virtual existing item' folder like MySisterProject above.

Ruben Bartelink
  • 55,135
  • 22
  • 172
  • 222
  • Nice one. This looks like a nice, lightweight solution, if you'll pardon the pun. – CAD bloke Jun 27 '12 at 13:56
  • @Cad bloke: It sure works alright (as does your pun :) , but there's a lot to be said for doing your utmost to avoid links in the first place – Ruben Bartelink Jun 27 '12 at 15:33
  • my reason for multiple projects is that AutoCAD extensions need different DLL references for different versions. There are also some API changes (yay extension methods!). Here's a couple of relevant links: http://www.theswamp.org/index.php?topic=41850.0;all & http://www.theswamp.org/index.php?topic=41868 – CAD bloke Jun 28 '12 at 03:51
  • @CAD bloke: Sounds like you're in a land where there are not many easy ways out so! (I was trying to prod in the direction of having assemblies which depend on abstractions, and then the Composition Root stuffing in a relevant adapter as being a cleaner impl, but sometimes that just doesnt seem feasible. Having said that, it's always worth assessing if its worth doing right this time as there's inevitably a refactoring tool or VS getting confused when files are shared between projects etc.) – Ruben Bartelink Jun 28 '12 at 08:09
  • I found if you add or remove things from the source project the targets don't get refreshed in the Solution Explorer until you reload the solution. VS2010 & VS2012RC. – CAD bloke Jul 02 '12 at 06:46
  • 2
    @CAD Bloke: Yes, that one is fun. Just for clarity I'll say the following explicitly in case it helps someone... You can unload/reload a project to get it to pick up changes. (Alt-P, L twice). The VS2010 issue is that .targets files etc.` – Ruben Bartelink Jul 02 '12 at 08:48
  • 3
    Here's my latest version of the wildcard theme ... Src\%(RecursiveDir)%(Filename)%(Extension) – CAD bloke Sep 06 '12 at 02:11
  • @CADbloke or OP, please edit (or answer) to show how to add the XML references? I'm a long time coder but totally new to Visual Studio... Thanks. – Chris K Sep 03 '13 at 21:04
  • @ChrisK Manually edit the xxxx.csproj file. I also add the manual edits as XML comments so I can reinstate them if...when Visual Studio overwrites them. It tends to overwrite Environment variables, absolute paths and filename wildcards. – CAD bloke Sep 04 '13 at 00:39
  • @CADbloke That's a good 'Best PracticeTM' you have there - noted! @ChrisK If you unload the project in the VS solution tree, you get an Edit Project File menu option which will bring you into the `.csproj` file (or with the VSCommands plugin you'll always have it) – Ruben Bartelink Sep 04 '13 at 08:16
  • 1
    @ChrisK Here's some more clarification on my edits in the csproj file ... http://www.theswamp.org/index.php?topic=41850.msg472902#msg472902 . I just edit it in Notepad++. When I save it VS sees it has changed and asks for a reload. There are settings in VS to control this behavior. – CAD bloke Sep 04 '13 at 20:59
  • Be aware that this doesn't work when files have dependencies on other files. I wrote https://github.com/CADbloke/CodeLinker to get around that but it is still a complicated mess. – CAD bloke Dec 28 '17 at 07:18
18

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

John Saunders
  • 157,405
  • 24
  • 229
  • 388
  • I guess if I create a build event and publish the dll into the source controlled _lib folder in the referencing project, then check in that DLL it would work.. seems kind of hacky tho.. – hanzolo Oct 23 '14 at 17:30
  • 1
    If you want to source control every build, then you can have a build target check out the library dlls, copy from the build outputs into the library folders, then check in the dlls. – John Saunders Oct 23 '14 at 17:35
10

Extract the common code into a class library project and add that class library project to your solutions. Then you can add a reference to the common code from other projects by adding a project reference to that class library. The advantage of having a project reference as opposed to a binary/assembly reference is that if you change your build configuration to debug, release, custom, etc, the common class library project will be built based on that configuration as well.

Mehmet Aras
  • 5,106
  • 1
  • 22
  • 31
8

You could include the same project in more than one solution, but you're guaranteed to run into problems sometime down the road (relative paths can become invalid when you move directories around for example)

After years of struggling with this, I finally came up with a workable solution, but it requires you to use Subversion for source control (which is not a bad thing)

At the directory level of your solution, add a svn:externals property pointing to the projects you want to include in your solution. Subversion will pull the project from the repository and store it in a subfolder of your solution file. Your solution file can simply use relative paths to refer to your project.

If I find some more time, I'll explain this in detail.

Philippe Leybaert
  • 155,903
  • 29
  • 200
  • 218
  • In defining your projects, make sure to use only relative paths... That should, especially for a reusable one, solve more than a tiny problem. – xtofl Jul 12 '09 at 17:38
  • 5
    Just for reference, `svn:externals` hard links to a repository. When you move the repository, the external links still point to the old repository. – Andomar Aug 01 '10 at 16:13
  • For git you can use SubTree [SVN:externals equivalent in GIT?](//stackoverflow.com/a/571715) – Michael Freidgeim Sep 30 '17 at 01:03
5

It is a good idea to create a dll class library that contain all common functionality. Each solution can reference this dll indepently regardless of other solutions.

Infact , this is how our sources are organized in my work (and I believe in many other places).

By the way , Solution can't explicitly depend on another solution.

user88637
  • 10,850
  • 8
  • 34
  • 35
  • 1
    I believe this is one of the biggest points of the question which a ton of people obviously don't get. – Del Lee Mar 13 '18 at 22:37
5

If you're attempting to share code between two different project types (I.e.: desktop project and a mobile project), you may look into the shared solutions folder. I have to do that for my current project as the mobile and desktop projects both require identical classes that are only in 1 file. If you go this route, any of the projects that have the file linked can make changes to it and all of the projects will be rebuilt against those changes.

Stevoni
  • 341
  • 7
  • 18
  • How does that work Stevoni? Could you provide more information? – Steve Dunn Jul 09 '11 at 13:34
  • @SteveDunn I posted a how-to on my very rarely updated blog (stupid school and work get in the way of the fun thing in life). It can be found [here](http://stephensprograms.blogspot.com/2009/11/shared-file-between-project-types.html) – Stevoni Jul 12 '11 at 13:56
5

Two main steps involved are

1- Creating a C++ dll

In visual studio

New->Project->Class Library in c++ template. Name of project here is first_dll in 
visual studio 2010. Now declare your function as public in first_dll.h file and 
write the code in first_dll.cpp file as shown below.

Header File code

// first_dll.h

using namespace System;

namespace first_dll 
{

public ref class Class1
{
public:
    static double sum(int ,int );
    // TODO: Add your methods for this class here.
};
}

Cpp File

//first_dll.cpp
#include "stdafx.h"

#include "first_dll.h"

namespace first_dll
{

    double Class1:: sum(int x,int y)
    {
        return x+y;
    }

 }

Check This

**Project-> Properties -> Configuration/General -> Configuration Type** 

this option should be Dynamic Library(.dll) and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path 
where first_dll.dll is created and add the file.

Add this line at top in C# project

Using first_dll; 

Now function from dll can be accessed using below statement in some function

double var = Class1.sum(4,5);

I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.

Croko
  • 89
  • 1
  • 4
5

You can host an internal NuGet Server and share the common libraries that will be shared in other projects internally and externally.

Further on this read

Si Zi
  • 811
  • 9
  • 6
4

There is a very good case for using "adding existing file links" when reusing code across projects, and that is when you need to reference and support different versions of dependent libraries.

Making multiple assemblies with references to different external assemblies isn't easy to do otherwise without duplicating your code, or utilizing tricks with source code control.

I believe that it's easiest to maintain one project for development and unit test, then to create 'build' projects using existing file links when you need to create the assemblies which reference different versions of those external assemblies.

Jav_Rock
  • 21,011
  • 18
  • 115
  • 164
Rick Sipin
  • 41
  • 1
2

One simpler way to include a class file of one project in another projects is by Adding the project in existing solution and then Adding the DLL reference of the new project in the existing project. Finally, you can use the methods of the added class by decalring using directive at the top of the any class.

2

As of VisualStudio 2015, if you keep all your code in one solution, you can share code by adding a shared project. Then add a reference to this shared project for each project you want to use the code in, as well as the proper using directives.

wecky
  • 547
  • 6
  • 12
2

Now you can use the Shared Project

Shared Project is a great way of sharing common code across multiple application We already have experienced with the Shared Project type in Visual Studio 2013 as part of Windows 8.1 Universal App Development, But with Visual Studio 2015, it is a Standalone New Project Template; and we can use it with other types of app like Console, Desktop, Phone, Store App etc.. This types of project is extremely helpful when we want to share a common code, logic as well as components across multiple applications with in single platform. This also allows accessing the platform-specific API ’s, assets etc.

enter image description here

for more info check this

StayOnTarget
  • 7,829
  • 8
  • 42
  • 59
Hussein Khalil
  • 1,311
  • 9
  • 27