I have created an empty project and added two ( .cpp) items inside the project. Keep in mind that I am a beginner in C++ Visual Studio, so I have not used any code to somehow connect the two files.
Problem: The debugger was fine for debugging my first file, but when I open my second file and start running by clicking "Local Windows Debugger" (clicked when I was inside the second file), it will still keep on running the first file whether there was a bug or not.
When I looked at the debug window after I hit "Local Windows Debugger", I saw the file path pointing to the first file.
I have tried: Closing the first file completely, closing visual studio and opening my second file from my folder path, turning off the break-point in the first file and turning on in the second file.
I would like to know: How can I just run the second file? Do I have to use the command prompt to keep my two items in the empty project separate? I am using Windows 10 by the way.
I searched for my problem, but I had a hard time looking for a guide that gave a solution
Issue:
Dracep cannot debug one of two files they have. This is due to them having a main function definition in both files, causing the editor to favour one over the other.
Solution:
By having a third, dedicated entry point in your application (I.E. having a single point of entry you then include the other files), you can decide which file you are going to debug at any given time.
For example, having a file called main.cpp which then includes the other two files by using #include "filename.h".
From there you can include the file and make you code checks by calling the functions in that file rather than having a main and stepping down through it, causing long term issues of scalability.
Please see this question on separating your logic from your definitions, as the answer marked correct is the standard for most C++ projects you will find.
That way, you could do something like the following:
#include "File1.h"
#include "File2.h"
int main(int argc, char** argv)
{
File1Class file1Class;
File2Class file2Class;
//Do whatever tests you like with either.
}
Related
I have a C++ project in Visual Studio, and have added another project exclusively for testing. Both of these projects are EXEs (console apps). So how do I use the first project inside the second?
Just to clarify, the question here would be somewhat self-evident if the first project was a library that one could simply include in the second project but, being an EXE, this is where the problem lies.
Per your comments, you have a C++ console application (MyApp) for which you have developed some application-specific classes that you want to unit-test with googletest in
Visual Studio. How?
As you say, if you wanted to unit-test a library the way to do it would be
obvious. You would:
1) Create a project to create a unit-testing application (UnitTest).
2) Configure the include-search directories so that the compiler can find the library's headers.
3) Configure the library-search directories so that the linker can find the library itself.
4) Add the library itself to the linker inputs.
5) Make the UnitTest project dependent on the library project, so that building UnitTest ensures MyApp is up-to-date.
6) Code the UnitTest app per googletest docs.
But since the classes you want to unit-test are specific to MyApp, you don't have any
library.
A drill-sergeant answer to that is: You don't have a library containing the classes you want to unit-test? So make one!
That way you use 3 projects:-
MyAppLib, generating library that contains all the functionality you want to unit-test.
MyApp, generating the same executable as at present, but linking MyAppLib
UnitTest, generating an executable that unit-tests MyAppLib, also linking MyAppLib
However if you don't like the drill-sergeant answer you can work around it.
From the usual build-system point of view (the one designed into Visual Studio),
the important output of the MyApp project is the build-target - the .exe.
The .obj files generated are just intermediate by-products. VS offers you no support
for treating these by-products as automatic linker inputs of a dependent project, and if a dependent project was also an .exe of the same sort - as it is your case - then such automatic linkage would be impossible anyhow because the main entry point would be multiply defined.
But from the unit-testing point of view it's the other way round. The .exe is of no interest, whereas (some of) the .obj files wholly or partly contain the implementations of the classes you want to unit test. In the text-book case where class foo is defined in foo.h and implemented in foo.cpp, the object file foo.obj is needed in the linkage of UnitTest.
For simplicity, assume that MyApp employs just one application-specific class foo,
defined in foo.h and implemented in foo.cpp. Then you have two options for building UnitTest.
a) You can add foo.cpp to the source files of UnitTest. Don't copy it of course. Just Add an existing item from the source folder of MyApp. Then you're done, but this
course has the downside that foo.cpp is exposed to untoward editing within
the UnitTest project.
b) You can treat foo.obj just like a static library required for the linkage of UnitTest and follow steps 1) - 6) above. This means in particular at step 3) that the {Debug|Release} build of UnitTest is configured with library-search directories that include \path\to\MyApp\{Debug|Release} (either in relative or absolute form).
In reality, for option b), there's very likely more than one .obj file from MyApp that you will have to link in UnitTest, and quite likely that their number will grow with time. Maintaining the right linkage of UnitTest could become a chore, and you might come to the conclusion that the drill-sergeant was right after all.
Depends. Google Test is (primarily) a Unit Testing framework (oversimplifying, testing classes). You can absolutely use is for other types of tests, but it doesn't have "built in" functionality for other types of testing, you'll have to write it yourself.
If you are trying to system test your executable, than you can run the process. I suggest using Boost.Process if you are using a multi-platform system or already have a boost dependency. Else, look here: launch an exe/process with stdin stdout and stderr?
The "tests" you write will call the executable, and can input stdin or stdout accordingly.
For example:
std::string path_to_exectuable = "thepath";
TEST(FooTester,CheckHelpScriptReturns0)
{
using bp =::boost::process;
std::vector<std::string> args; args.push_back("--help");
bp::context ctx;
ctx.stdout_behavior = bp::capture_stream();
bp::child c = bp::launch(exec, args, ctx);
bp::status s = c.wait();
ASSERT_TRUE(s.exited())<<"process didn't exit!";
ASSERT_EQ(s.exit_status(),0)<<"Help didn't return 0";
}
I was in a similar situation and I set this up in a way that effectively accomplishes the same goal of Mike Kinghan's answer as far as the compiler is concerned, but goes about it a different way from the user's perspective.
What I did was create a custom Configuration that I called "Testing". You create a new configuration by opening the project settings, choosing "Configuration Manager..." and selecting "New..." in the configuration selection box.
When prompted, I chose to copy the settings from the default "Debug" configuration, so that I can use the debugger with my tests just the same as if I was in the "Debug" configuration.
Under the new Testing configuration, I set the options for the compiler and linker to use google test as you normally would.
The important change in the properties is that I define a preprocessor variable which I have called "TESTING".
I rewrote my "main.cpp" to look something like this:
...
// includes
// functions
// whatever
...
#ifdef TESTING
#include <gtest/gtest.h>
#endif
int main(int argc, char **argv) {
#ifdef TESTING
::testing::InitGoogleTest(&argc, argv);
int val = RUN_ALL_TESTS();
getchar(); // not necessary, but keeps the console open
return val;
#endif
// rest of main() as normal...
}
What I'm trying to indicate is that I only changed a few lines right around where main is defined, I don't have to make gross changes spread throughout the file.
Now that this is all set up I simply made a new source folder for my tests, and create ".cpp" files in there. To avoid bloating the normal executable, I wrap these files with a check for the TESTING variable, so I have something like this:
tests/Test.cpp:
#ifdef TESTING
#include <gtest/gtest.h>
#include "my_class_header.h"
TEST(TestMyClass, test_something) {
// perform some test on class
}
#endif
I think these files still get "hit" by the compiler under Debug and Release configurations, so having a ton of these might slow down the build, but the Debug and Release objects wont get bloated with testing code.
The two takeaways are:
Using this method, the testing code is still organized separately from the application code, but it still resides in the same Visual Studio project, which may or may not be beneficial. Personally I like not having to manage/worry about a second project.
Like Mike Kinghan said, managing and linking .obj files yourself can become a chore, but by using this method, the default Visual Studio settings manage this for you.
One downside is that effectively redundant copies of all object files will get created in the "Testing" output directory. With more configuration, surely there must be a way to "share" the Debug object files, but I didn't have a reason to go that far.
This is a very simple method which may be a lot easier than refactoring your application into separate libraries and a main. I don't love using preprocessor wankery, but in this case it's fairly straightforward, not too much code bloat, and accomplishes exactly what it needs to. You could always trigger the tests another way, without using the preprocessor.
If you are not very rigid about having the tests in a different project, you can write the tests in your application project. Then just make the application execute the tests when receiving certain command line arguments, and execute the normal application logic otherwise, i.e.
int main(int argc, char* argv[])
{
if (argc >= 2 && std::string(argv[1]) == "--tests")
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
else
{
// Application logic goes here
}
}
TEST(ExampleTests, TestSQRTCalculation) // assuming all the right headers are included
{
EXPECT_NEAR(2.0, std::sqrt(4.0), 0.000001);
}
This avoids creating an unnecessary library for the sole purpose of testing, although you can still do it if it is correct structure-wise. The downside is that the testing code goes into the executable you are going to release. If you don't want that I guess you need an additional configuration which specifies a pre-processor directive to disable the tests.
Debugging the tests or running them automatically at post build is easy, simply by specifying "--tests" as debug args or at post build command line respectively.
If you want to test a console app you can run a test that opens a console window and run the exe file of the first app.
Then in your googletest catch the standard output from the exe you just ran.
[For more control over the first app you might need to have the first app parse arguments sent to it, e.g. some flags like -x or what ever you need.]
I have prepared a github repo including Visual Studio 2015 solution in parralel of Mike's "drill-sergeant" suggestion. You can use it directly without any additional requirement or dependency.
https://github.com/fuatcoskun/GoogleTestVS2015
I hope it helps...
I do not regularly write code. There are times I write code daily for 6 months, and then do not code for up to 2 years. This approach has forced me to keep a bunch or reference code that I (and other much, much better programmers) have written. I refer to this "library" when writing code after a long period; I read it, I execute it, and that is a massive help in refreshing myself. This system has served me very well with Eclipse & Java over the past 5 years.
I am now learning C++ and am using Code::Blocks. I would like to somehow stuff a bunch of C++ files that have main methods into a single Code::Blocks project. I am willing to rewrite the code to achieve this task (if it's reasonable...)
I am not the first to look for a meaningful answer for this issue: https://stackoverflow.com/questions/35917504/how-can-i-make-multiple-programs-in-a-single-project-in-codeblocks and https://www.reddit.com/r/learnprogramming/comments/3opp5r/how_to_run_multiple_cpp_files_separately_in_same/
I do not want to change the IDE or compare it to other IDEs. What I am looking for, is the ability to execute one of hundreds of tiny programs that are in a well organized in an expandable file tree in C::B quickly and easily. If I put each C++ file with a main in it's own project I will have so many C::B projects that it will be unreasonable.
I do understand that C::B is not Eclipse and C++ is not Java, and that C::B is intended to have a single c++ file with a main function per project.
Any answers, and even very creative answers would be very appreciated! Scripts, settings, how to rewrite my code, whatever - if you have a suggestion I would love to hear it so I may consider it.
In the interest of full disclosure, currently I am keeping all my tiny programs in directories and use the O/S to drill through the directories and simply double click on the .cpp file which C::B opens. I am willing to dramatically modify my code to be able to achieve the objective.
Thanks for your time.
To compile and run a single main() file in a Code::Blocks project with multiple main() files:
In the "Projects" tab on the left, right-click on a file that you do not want to compile.
In the menu that appears, point to Options, and uncheck both Compile file and Link file.
This has to be done for all the files that you do not want to compile.
Now, when the project is built and run with F9, only the desired file will be compiled; the others will be ignored.
Note: It is not necessary to create a project in Code::Blocks to compile and run single file. To compile and run single files (without creating projects)
Just click on File -> Empty -> New file.
Save the file with .cpp extension anywhere (not in a project).
To compile and run the file, just press F9 or Build -> Build and run
However, such files (without projects) cannot be debugged. The most appropriate thing would be to just have a project with multiple main() files, as explained in the early part of this answer.
I've learned Java before, and am starting to learn C++ now.
When using Code::Blocks as my primary C++ IDE, I met the same problem as you. Although I found nothing useful on the Internet, I managed to figure it out on my own. Here is my solution.
In your Management panel, find your current project and right click, choose Close Project. (We won't use project to manage our code for this purpose.)
Still in the Management panel, find the Files tab, navigate to your working directory, right click on it and choose Make Root.
And we are done!
When you want to add a new code file, right click on your folder and choose New file..., enter your file name with the extension of .cpp. Then you can just use your C::B as before. Without the limit of project, C::B will just compile your current C++ file and run it on its own. Keyboard shortcuts F9 and the Run and Build button still works.
The only disadvantage is that you can see .exe and .o files in your file list, which is a little untidy. I'm still trying to find how to hide them in the list.
Hope this will help you.
How about using the precompiler? You can surround each main with:
#ifdef EXECUTE_EXAMPLE_1
int main() { return 0; } // example of one of the "mains" in one cpp
#endif
#ifdef EXECUTE_EXAMPLE_2
int main() { return 0; } // another "main" in an other cpp
#endif
#ifdef EXECUTE_EXAMPLE_3
int main() { return 0; } // yet another "main" somewhere else
#endif
And creating a header, included by all "mains" where you can define one to run:
#ifndef _EXECUTION_HEADER_H_
#define _EXECUTION_HEADER_H_
// Uncomment one and only one
#define EXECUTE_EXAMPLE_1
//#define EXECUTE_EXAMPLE_2
//#define EXECUTE_EXAMPLE_3
#endif // _EXECUTION_HEADER_H_
This could be a quick and dirty "build system" for your usecase.
I think this is what they were trying to accomplish.
No, you can't have two main files in the same Project, but you can have a lot of smaller project programs saved to a workspace which allows you to run and test them each individually.
https://www.youtube.com/watch?v=cHGIIp3rGO8
I am having a very strange problem with Visual Studio 2008. I searched here on SO for similar problems with the "Project Out of Date" dialog, but their problem was that either they were using a header file that is deprecated/no longer exists, or their problem was occuring while building a multi-project solution or it had other dependencies.
My project is a Win32 Console application, I went to File->New->Project...->Win32 Console Application. I used the default settings (precompiled header is checked), and I didn't change a single line of code in the project, as soon as the project created I pressed the debug button (though I get the exact same problem when I set the build target to Release).
[main.cpp]
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
^ Very standard source file, right? Well, no matter what I build in any project VS2008 tells me it is out of date. Why? This problem may not prevent me from building the project, but I would very much like everything to be in order and never have to see this dialog again. Again, I looked at similar questions, but their solutions involve removing some extra dependency or something of the sort, none of which applies to my situation.
Why might VS2008 be nit-picking on its own project template?
If a source file (including include files) somehow got a date time some time in the future, then the compiler will think the object files are always out of date.
I want to examine a lot of little cpp files that have int main() , and run only one of them at one running . something like this -
Is there any way to do that without open new project for every cpp file ?
You can choose not to compile the files. Go to the properties, and exclude the file from build.
No. In a project, you cannot have multiple main() function.
You can rename them to test1(), test2(), test3(), and call them one by one from main(). That is what I do usually.
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.
Edit: Whilst not necessarily a solution, the work-around provided here:
How to get IntelliSense to reliably work in Visual Studio 2008
Is probably the best bet if I want a decent IntelliSense system.
Native C++ intellisense does not work reliably in any version of Visual Studio. I find there are two common problems:
1) Header file paths are not set-up correctly. When you find a type where intellisense is not working, use the IDE to click through each header file to find the one containing the type. (Right click on #include and select Open Document...). If this fails before you get to the file which declares the type then this is your problem. Make sure header file search paths are set-up correctly.
And,
2) The intellisense database is corrupt. This happens ALL The time. You need to close the solution, delete the .ncb file, and then reopen the solution. I posted the macro I use for this in answer to another question here.
The preprocessor can also confuse intellisense - so make sure any #defines during build are also available to intellisense. Other than that, I don't know what else can break it. I've not seen any particular issues with forward declarations.
I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea.
This is why we have bought Visual Assist (from Tomato software) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages)
This is not a solution, just a workaround.
It looks like there's hope on the horizon for those of us unable to obtain Visual Assist:
Rebuilding Intellisense
Do you have any add-ins installed (or uninstalled)? I find that effects my intellisense.
Besides that just making sure your Tools->Options->Text Editor->All Languages "Auto List Members" and "Parameter Information" are checked off.
I don't use VS2008 for C++, only VB & C#, but I find that when intellisense stops working (true for VS2003/2005/2008) it's because something in the project/file is broken - usually a bad reference or code.
VB and C# have much better intellisense support due to the ability to reflect on the referenced assemblies to build the intellisense tree.
C++ has to walk the include files for function prototypes, and if the paths are not correct it will not find all the prototype headers.
My fix to itellisense was required after that awful refactor utility minced my code. The problem was a class header file that included an #include of itself. The recursive reference destroys itellisense. A symptom of this is if itellisense can see other classes but not the current one. Also:
Use #pragma once to eliminate duplicate header loads
If the project now takes a very much longer time to load, that itellisense trying to make sense of the conflict that is causing then lack of completion support.
Often it is only one class object that is affected, This shows you what files (usually headers) to look at.
#John Richardson / #Jonathan Holland
My includes are setup correctly, no problems there. I've also tried the NCB rebuild several times but it never fixes it 100%.
I have a feeling it may be to do with forward declarations of classes. e.g. to reduce the complexity of includes in header files we normally do something like:
class MyPredeclared;
class SomeOtherClass
{
private:
MyPredeclared* m_pPointer;
}
I wonder if that screws it up? Any other ideas? It definitely gets worse the larger your project gets.
I had a very annoying problem, intellisense was working only in some files, without any evident reason... it took me a couple of hours of digging through google, but I finally understood that the reason was indeed recursive reference!
I was using the:
#ifndef CLASS_H
#define CLASS_H
...
#endif
to avoid redefinition of symbols, and this sometimes breaks intellisense in big projects.
But it is enough to comment the ifndef-define-endif and put a:
#pragma once
at the beginning of the header files to still avoid redefinitions and have Intellisense working again =)=)
At least, this worked for me, hope it's useful...
Cheers
Francesco
I have recently studied Intellisense in VS2008, as I'm developing a rather large C++ numerical linear algebra library where templates and such are used extensively. Intellisense stopped working shortly into the project and I sort of gave up, but now it became really annoying without it so I set to investigate. This is what I found out:
Assuming there is a file(s), containing code that "breaks" Intellisense,
if header files that break Intellisense are in the project, but are not #included, it still works in the rest of the files
if they are included, but no type declared inside is used, it still works
if they are included and a type declared inside is used, it might still work a bit (no Intellisense for members, no Intellisense after occurrence of given type, but at least global names and argument info before)
if Intellisense is broken in one .cpp file, it can still work in the others where the problematic code is not included or used (but i imagine if it crashes bad, it will get disabled for the whole project, although that did not happen to me)
Intellisense seems to be updated after successful compilation (sometimes not before)
putting broken code inside any of #if 0, /* .. */ or // seems to put Intellisense at ease
From the C++ features I used, actually only a few break Intellisense:
comparison with '>' or '>=' in template parameter (e.g. static_assert<(size > 0)>)
not solved by using double parentheses (static_assert<((size > 0))> does not help)
solved by using '<' or '<=' instead (static_assert<0 < size> works)
solved by storing the value in enum and using that to specialize the template
explicit function template specialization disables argument info (e.g. function<type>(args))
probably unable to solve (maybe wrap in a macro), but I can live with it being broken
instantiation of template member type, such as Matrix::MakeMatrixType<3, 3>::Result r;
kind of hard to figure out exactly why this happens (likely because of use of Eigen)
workaround by moving such code in a separate .cpp where IS won't work (not always possible)
It would seem that some of those problems are due to some "simplified" parsing, which is less strong than a proper C++ parser. With the above information at hand, a "reliable" method of making Intellisense work in an existing code:
Set up an empty project (a console app), create Main.cpp with dummy void main() {} in it.
Include one of your broken header files, and math.h
Build (it must compile, in order for Intellisense to update reliably)
Test whether Intellisense is working by typing e.g. sin( and seeing if argument help pops up. Sometimes, this would work, but member help wouldn't - so try that as well.
Make an instance of something in the header file, build, see if that manages to kill IS.
Remove code from the culprit file and go to step 3
After finding and fixing problematic code, put back code removed in step 5, try again
After making a whole class work well, make an instance of the next class, and so on ...
I found it easy this way to pinpoint locations of code that made problems (I realize that this might be unfeasible for really large projects, in my case only a single file out of 97 made problems). Note that 'Build' here refers to compiling, the linking stage does not need to finish, so unresolved externals are ok, the IS should update regardless.
Another method of updating IS (other than building) is to save everything, close workspace, delete .ncb file and reopen it. Then wait for 'Updating Intellisense ... (N)' to disappear from the status bar (N counts towards zero, if it doesn't go all the way, it kind of shows progress where problems occurred). I found this rather tedious.
About this problem i've notice something interesting (on Visual Studio 2010):
to solve this problem i've changed #include sintax in my header files, before was (old project done with VS 2005 and reopened using VS 2010):
#include <myfile.h>
and i fix this with:
#include "myfile.h"
After intellisense start working correctly!
I hope this can help!
I had to reset the settings...
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE>devenv.exe /ResetSettings
thread on this here
The problem is with the .vcproj files.
You will find if you switch to release mode from debug mode, build, then try intellisense it often works.
Close Visual Studio. If you search for the .vcproj files in your project, edit them and search for the first two instances of AdditionalIncludeDirectories. The value for this should look something like "..\,....\" rather than "../..".
Reopen your project, let the Intellisense finish building, then it should be fixed.