How do you add a C++ project reference in Visual Studio? - c++

In C# it's pretty simple to add a project reference that will build the dependency, put the resulting assembly in the original's Debug/ directory and properly compile against that assembly.
So at the moment, I have a project with the Main() and a static library project in one solution. However, when I compile the Main() project and I look in the bin/Debug/ directory I don't find either the Static.lib file or the .obj files, which I think would need to be there, or something... I'm getting linker errors.
I think maybe I have to Configure the project to find the .obj and the .lib file produced by the static library project (which compiles fine, and actually produces those files.)
I'm missing something, and I'm not very well versed in Visual Studio with C++.
How do I add the reference in the Main project to use the library produced by the static library project?

The first thing you'll have to unterstand is, that static libraries are nothing like .NET assemblies. They are linked into the .exe and are not distributed as separate entity.
Your linker errors are most likely a result of you not linking to the library.
There are several ways to define libraries that have to be linked.
One is int the project settings under linker -> input -> additional dependencies,
the other would be the cheap route via #pragma comment(lib, "path to library")

You can add the name of the .lib files you need by going in project property->Linker->Input->Additional Dependencies
Then you will have to give the folder where your library is in VC++ Directories->Library Directerories.

Here is a very comprehensive answer: visual c++: #include files from other projects in the same solution
It describes the settings for the linker but also other essentials when referencing another C++ project. (especially when coming from C# but not being too versed in C++)

In .NET, one of design goals was due make this process a lot easier and automatic. Mission accomplished there.
In the native C++ world, the process is much more manual. Here is roughly my process for hooking up different modules together.
Include all relevant modules in the solution.
Set the output
directory of each project to the same directory. Either Right click
on each project, choose properties and in general, set the output
directory to: $(SolutionDir)\Bin\$(Configuration)\$(PlatformTarget).
For reduced headaches, Set this for all configurations and platforms.
Then all the files will be placed in somewhere like
\your-solution\bin\Debug\x64.
Set the project dependencies - Right click on each project that will be linking to another -> Choose Build Dependencies and select the referenced projects.
Set up the linking process, by Right clicking on the calling project and choosing
properties. Go to linker -> Input and add: $(SolutionDir)\Bin\$(Configuration)\$(PlatformTarget)\MyLibrary.lib
For the actual functions that are going to linked to, I set the
function declarations to something like (There are a lot of variations on the function declaration, a bit outside of the scope here):
#define DllExport __declspec( dllexport )
extern "C" void DllExport WINAPI` Testing();
In actual cpp file of the calling function, I add something like the following:
#include "..\MyLibrary\mylibrary.h"
Then in the actual calling function. simply add called function:
Testing();

If you are building multiple projects in the same solution, use a project reference to automatically link your libraries and executables together:
https://learn.microsoft.com/en-us/visualstudio/msbuild/common-msbuild-project-items?view=vs-2019#projectreference
which is explained pretty well here:
https://milania.de/blog/Project_references_in_Visual_Studio_and_C%2B%2B
The advantage to this approach, is that the build order will be correct. Using Additional Dependencies, as suggested in the other answers, will not maintain the proper build order.

Related

How to link and built a project when your external SDK only has .dll, .lib, .h files

I have an external SDK that only contains a .dll, .lib, and .h files. I'm trying to use the SDK. Nothing in the dll is readable, but the .h files have some comments about the methods.
I'm not very c++ savvy. I assume I need to load the library, then read from the dll using the methods that are defined in the .h files. Correct?
I need to know how to write a cpp project where I can link all these files, read the dll, and be able to use the methods that are defined in the sdk.
Is there a test project with the project setup where I can see how this can be done?
Any help would be appreciated.
There's several ways to achieve this, including a shortcut method using #pragma that I'm not going to recommend in case it leads you to develop poor habits.
Similarly, you can use Property Sheets, but that may seem a bit overwhelming to start with. So I'm going to give you the standard middle-of-the-road approach...
In your project settings (Alt-F7 or Project > Properties...), you need to set these options:
C/C++ > General > Additional Include Directories
Add the folder you want to be searched when using the #include directive. Without complicating this with personal preference and style considerations, just set this to the directory where the SDK's header file lives.
You can use absolute or relative paths, environment variables. Whatever. I suggest for now you just use absolute path.
Linker > General > Additional Library Directories
Same as above, but this is where the .lib file resides.
Linker > Input > Additional Dependencies
This is the name of your lib file.
Now, if you #include the SDK's header file in your project's source and compile, it should hopefully work. And the linking step should also succeed.
If not, there may be extra things you need to make the SDK play nice (such as preprocessor definitions, compiler settings, or additional dependencies).
The last thing you need to worry about is that running your program might fail because the DLL cannot be found, unless it lives in a specific place that Windows searches. Rather than mess with DLL search paths etc, you can use a Post-Build Event to copy the DLL to the same directory where your executable was built.
Still, in the project properties:
Build Events > Post-Build Event
Add a command line something like:
copy "\Path\To\MySDK\MySDK.dll" "$(OutDir)\"
Now you should be all set to go, and not have to think about it again!

Create a Second C++ Project in Visual Studio 2010

I am looking for detailed steps to create a second Static Lib Project in Visual Studio 2010
that my first project will reference.
This project will be in source control and used by others so the referencing needs to be able to work on all folder structures. (if possible)
I have done this before but have had problems recently. I mostly end up adding random references to everything and every folder in my project until it works as I do not know the correct steps to accomplish it.
This will be my projects folder structure
<Whatever Structure>/MyProject/MainProject
<Whatever Structure>/MyProject/SecondProject
<Whatever Structure>/MyProject/MyProject.sln
I need my SecondProject to be built as a Static Lib library.
Inside my FirstProject I would like to reference files from my SecondProject as
#include <SecondProject/<filename or class or namespace>
As I said above Detailed Steps to accomplish this would be greatly appreciated.
I have searched many other posts but most just pertain to Header Files or they are half the steps.
Thank you.
#include is solely used for headers. This is parsed at compile time. Since you want to use headers from <Whatever>/MyProject/SecondProject as just SecondProject/, obviously <Whatever>/MyProject/ must be among the include directories. Probably the best way to specify it would be as just ../, because that means you don't have to hardcode <Whatever>
After compiling, the next step is linking. The easiest solution here is to go the the property pages of MainProject, Common Properties > Frameworks & References, and use [Add New Reference...] button. Linking will make the compiled functions inside the .lib available.

How can you Call a method from a diffrent Project, both in C++?

I'm normally working in c# so certain things in c++ keep confusing me alot (they seem so diffrent yet the names almost the same)
I created a Console project in which i want to run a diffrent project for testing purposes. i added the project as a reference to the console app, and then got kinda stuck.
there is no namespace in the projects, so i can't do a using and if i try to include the other file, it cannot find it (and i want to avoid being unable to debug through it all).
the code for the class can be found here(ignore the c# part), the console is just a standard console with nothing in it yet.
Yeah, C++ doesn't have the notion of assemblies that exists in C# and .NET. It makes tasks like this slightly more difficult, a virtue of the fact that C++ compiles directly to native code.
Instead, you'll generally #include the necessary header files (*.h) at the top of your code file, and instruct the linker to link to the appropriate .lib file(s). Do that by going to your project's Properties, selecting Linker -> Input, and adding the file to the "Additional Dependencies" section.
As an alternative to linking to the .lib file, you can use Visual Studio to add a reference to the other project, if it's part of the same solution. Microsoft has a walk-through on creating and using a dynamic link library in C++ that might be worth a read.
I'll assume you're using Visual Studios:-). You have to tell
the compiler where to look for its includes. Under Visual
Studios, open the properties page for the project, then go to
Configuration Properties->C/C++->General, and add the necessary
directories in the entry Additional Include Directories. (If
the other project is in the same solution, use a relative path.
But I think the dialog box that pops up when you click on the
button on the right does this automatically. I'm not a great
fan of all this GUI stuff in general, but Microsoft seems to
have done this particular part quite well.)
Once you've done this, you might have to go through a similar
process for linking: this time it's under Configuration
Properties->Linker->General, and the entry is called Additional
Library Directories, but the principle is the same. (This may
not be necessary, if you're putting all of the dll's and
executables in the project in the same directory.)

.lib linking other .libs

Currently my visual studio is basically generating Engine.dll and Game.exe
Engine.dll links to some other basic libraries like:
d3dx9d.lib
ComCtl32.lib
WinMM.lib
WSock32.lib
etc.
I also wanted to try to create an Engine.lib, but I get some really nice warnings now: Symbol x has been defined already. These libraries define the same symbols.
So I read somewhere that I must force my user (Game.exe) to link to the libs instead. But this is just really inconvenient I think, especially if I have many games and I decide to add another library to my engine. It's just maintenance for something so simple.
Should I stick to the .dll, or is there some way to fix this beauty up?
Thanks a lot,
Antoon
You need to make up your mind whether the want the DLL or the static link library. Advantage of a DLL is that the build times can be quicker if you make local changes. Advantage of a .lib is that you'll end up with only one deployable file.
Getting it linked (either the static .lib or the dll's import .lib) is otherwise automatic. You want to make sure that the library is built first, can't link the .exe without it. Right-click the exe project in the Solution Explorer window, Project Dependencies, tick the library project. That automatically adds the .lib to the exe project's additional dependencies.
Using #pragma comment(lib, "engine.lib") in the engine's header file is another way. Repeat for other dependencies like the OS import libraries. Getting the library path right is a // todo item.
Did you create a different namespace to avoid naming clashes?
EDIT -- seems like there is some confusion as to what you're asking, because you are asking a couple of questions.
To me, it sounds like you want to take a stab at implementing your own Engine class. However, you've got naming issues. I am treating this as more of an architectural question now. If you write your Game to an interface, then the problem goes away. For example, if your Engine is using different algorithms, then if you had written an EngineInterface that the current Engine and YourEngine implemented, then you could easily use Strategy to flip between the different implementations on the fly. This is nice because you'll be able to see the differences in-game if you wire the preferences into the app.
If the symbols are not supposed to be the same, use diferent names or control how they are exposed. Another option is the usage of namespaces to avoid naming conflicts.
If the symbols are supposed to be the same thing, you need to define those only once in one of the libs.

Visual C++ TDD setup

I haven't worked much with Visual Studio before. I've started a personal project in my spare time and I would like to use test-driven development since it has been a huge benefit to me in my Java development. I started this project quite a while ago, and I used CppUnit. I know there are probably other frameworks that are better, but this is what's already in place.
My Visual Stuido 2005 solution has 2 projects in it. It worked fine when the unit tests resided right alongside the application code. As the project grew in size, this became quite cumbersome and inelegant. I created a new project under my solution to house the unit tests (so it now has 3 projects). Everything went fine until I tried to build the solution. Everything compiled, but the unit test project failed to link. The output gives me 51 "unresolved external symbol" errors (LNK2019) for what seems like every function that my tests call.
As far as I can deduce, the problem is the directory structure that Visual Studio creates. Each project gets its own directory, and then below that are the object files and executables that get created. I think the problem is that, while the header files are properly included in each unit test, the linker can't find the cpp files because they are in a different directory. When it fails to find the implementation of a called function, it gives me the 2019 error.
Am I right in my evaluation of the problem? How can I fix it? Do I need to completely reorganize my projects or is it a simple configuration of the linker?
Thanks
Yes, your evaluation sounds pretty good. Try this: In the solution explorer, right click the name of the project that contains your tests and choose "Project Dependencies". Put a check by every project that it is dependent on. That should set up the linker settings so it automatically can find the correct files.
It sounds like the functions/classes that your test project is using from your main projects aren't exported. If code isn't exported, then nothing outside of the DLL/exe that the code lives in can reference it.
A common way that we handle this is to add a define to the project (in the project settings, go to Configuration Properties -> C/C++ -> Preprocessor, the first line has the defines) called something like PROJECTNAME_IMPL (make sure you do this for both Debug and Release configurations!). Then there is a header file (called ProjectNameExport.h) that anything exported includes, which contains something like the following:
#ifdef PROJECTNAME_IMPL
#define PROJECTNAME_API __declspec(dllexport)
#else
#define PROJECTNAME_API __declspec(dllimport)
#endif
Then, when defining a class (for example):
#include "ProjectNameExport.h"
class PROJECTNAME_API Foo
{
};
This has the result of exporting the class when the header file is included in a file within the project, and importing the class when the header file is included in a file in another project (that links to the first project, of course).
I always add the code to be tested to a separate static .lib file, and have the main application EXE and unit tests EXE depend on this. New code is added the .lib project, and the dependency support ensure the EXEs link with no errors. You need to make sure the EXE projects can find the .lib headers, but this will depend on your directory structure. You also have to watch that that the .lib and the EXEs are using the same CRT/MFC library (for example, when using the CRT you can statically link with it or use a DLL).
I find using libs in this way easier to maintain than adding files/headers to multiple projects.
I am using the Boost test framework but I would structure this the same no matter the TDD framework.
A good article on a similar setup can be found here:
http://www.codeproject.com/KB/architecture/Designing_Robust_Objects.aspx