Why my Visual Studio failed to find definition? - c++

I'm trying to read some code(those code depends some unavailable lib so I'm not able to compile them, luckily I only need to read them) and using VS community 2017 15.7.5. I download the whole thing from github and use File->Open->Folder to import the whole folder. I found that when I try to find definition of a function(using F12), VS always jump to the declaration in the head file, even the .h file and the .cc containing the definition are in the same folder. What can I do to solve this problem?
Here's a simple demo:
main.cc:
#include "test.h"
int main(int argc, char *argv[])
{
foo();
}
test.h
void foo();
test.cc
void foo(){}
putting everything in one folder and open using operation above, no matter I use F12 or Ctrl+F12, VS only open test.h but not test.cc.

Instead of F12, try ctrl + F12. LINK: Default Keyboard Shortcuts in Visual Studio

Related

How can I create a c++ header file in Visual Studio Code?

I have a program with 3 files, and when IrRun the program via Code Runner it keeps printing errors.The icon for the "Log.hpp" file is C, not C++. It doesnt matter if I rename it to Log.h or anything, it seems that I cant create a c++ header file in vscode.
The 3 files are:
main.cpp
#include <iostream>
#include "log.hpp"
using namespace std;
int main() {
InitLog();
Log("Hello World");
return 0;
}
log.cpp
#include "log.hpp"
#include <iostream>
void InitLog() {
Log("Initializing Log");
}
void Log(const char *message) {
std::cout << message << std::endl;
}
log.hpp
#pragma once
void InitLog();
void Log(const char *message);
The error mesages are:
main.cpp: In function 'int main()':
main.cpp:5:5: error: 'InitLog' was not declared in this scope
InitLog();
^~~~~~~
main.cpp:6:5: error: 'Log' was not declared in this scope
Log("Hello World");
Need help.
Are you using Windows? Which compiler? Do you have Microsoft Build Tools installed or even Visual Studio? Are you using gcc or clang?
You must start VS Code from a developer prompt: Open a developer prompt console, navigate to the folder where you code is. Then enter
code .
Visual Studo Code will then open with the environment set up. Then open a terminal inside VSCode using Control-` and try
cl /EHsc main.cpp log.cpp
And it will create main.exe. You can run it in the terminal and it will not close... Next time you open the project you can just open the folder in VS Code, since it would then already have the json config files created
VS Code is just an IDE. So compilers must be installed and also extensions. And some JSON files and tasks must be set up. It is sometimes simple, sometimes not so simple, I believe. But doing that you will then have a powerful editor and an unbelievably flexible environment, since you can for instance run and debug code in nodejs or C or C++ or anything and even in Linux without leaving the session on your casual Windows machine.
Your question is about a specific vscode plugin called Code Runner. It's not really related to vscode. The way how Code Runner is designed will never work for multiple C++ source files. It's not the right tool for the job.
Perhaps you'd better off with Microsofts CMake Tools package for vscode. It does require you to create your own CMakeLists.txt file though. In your case you'd need nothing more than:
add_executable(log
main.cpp
log.cpp
)

VSCode IntelliSense proposes a .h file but marks it not found

I can't compile a simple stupid demo "project" using visual Studio Code.
As I'm trying to enrich my knowledge portfolio, I trying to learn the basics manually, as to speak I try to compile code manually, without that the Visual Studio Enterprise IDE does all automatically. So I decided to use Visual Studio Code on Mac + clang++ for a simple demo project.
My problem is: I have a Workspace. In this workspace, I have some directories. One Of those directories called Functions and Headers contains again directories: debug, release, include, src. In the src directory, I have the functions.cpp file containing two dummy methods:
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
and in the main.cpp:
#include "functions.h"
int main()
{
int x = add(1, 3);
int y = subtract(5,1);
return 0;
}
In my include folder I have two method declarations:
int add(int x, int y);
int subtract(int x, int y);
The interesting point is: When I'm in main.cpp and I type #include " then IntelliSense finds the functions.h and proposes that file to me.
Also, the method calls are highlighted correctly. But: after including the file, Visual Studio Code marks the file read and says: functions.h file not found.
Is that a visual Studio Code bug? Because I also had a look on the settings and the settings seems ok (see picture).
Clang writes:
Ginos-MBP:src ginovalentinopensuni$ clang++ functions.cpp main.cpp main.cpp:2:10: fatal error: 'functions.h' file not found
#include "functions.h"
^~~~~~~~~~~~~ 1 error generated.
Do I miss something or am I doing something wrong? I also looked at the other similar questions here, but there was nothing helpful.
Pictures:
Indeed. The VSCode include path that allowed #include "functions.h" to be autocompleted has no bearing on what is a valid path to the compiler. There are two ways to address this:
Fix the path in the source file
Since you are including the header functions.h from the ./src directory, try instead writing:
#include "../include/functions.h"
int main()
{
int x = add(1, 3);
int y = subtract(5,1);
return 0;
}
This should work. Unless a specific include path is given to the compiler, clang++, like most other C++ compilers, will interpret the path relative to the location of the source file. In this case, it needs to go up a directory and then into the include directory in order to locate the functions.h header file.
Add an include path to that of clang++
From reading the clang++ man page, it can be ascertained that the -I flag may be used to specify an additional include path for the compiler to search to find header files. So, assuming that the command was run from the ./ directory, one jump out of the src directory and the root of the project:
clang++ src/main.cpp -I./include
would also address the issue at hand.

Default code in each new cpp files in Visual Studio 2015

I am currently studying C++ using Visual Studio and I don't want to use a new project for each and every small topic that I go through, instead, I have one project into which I Add and Remove Cpp files as needed.
I wonder if there is a possibility to set a default piece of code into each newly added Cpp file so that I donĀ“t need to copy it every time. Some simple code like this
#include <iostream>
using namespace std;
int main()
{
cin.get()
return 0;
}

Eclipse CDT Including Unreferenced Files in Automatically Generated Build

I'm new to cpp in eclipse and trying to mess with simple builds. I have made a basic project which automatically generates build info (no user-defined makefile).
Simple (Working) Case
I made a "Hello World" project called Test (not an empty project). It has one file - Test.cpp with a main() in => builds and runs fine.
Test.cpp
int main() {
// output some stuff
}
Slightly More Complex (Working) Case
I make a new file called Main.cpp. Move the main() function into Main.cpp and make a decleration of a function in main too - void test();
The test() function lives in Test.cpp, which is where I provide the function definition.
Main.cpp
#include <iostream>
void test();
int main() {
// Use test()
}
Test.cpp
#include <iostream>
void test() {
// output some stuff
}
Build it, there are now two .o files in the Debug directory - Test.o and Main.o. This runs fine.
The Problem
Now I try to introduce a third file - Limits.cpp.
Limits.cpp
#include <iostream>
void printLimits() {
// Print out limits for different integer sizes
}
Again I provide a deceleration of this function in Main.cpp.
Main.cpp
#include <iostream>
void test();
void printLimits();
int main() {
// Use printLimits()
}
This time there is no object file created for Limits in the Debug folder => the build fails.
Main.cpp:*line* undefined reference to `getLimits()'
It just looks like the autogenerated build config for the project is duff. I've tried looking around the project properties but I have had no luck. I've tried including the path/file in Include Paths/Include files, other objects, and I've checked just about every other property I can see. This has been frustrating me for two days.
The strange thing about this is case 2. It looks like because Test.cpp was the first file made it always includes this in the build? (even if it is not imported). Where as because Limits.cpp is new and not imported it doesn't generate an object file so it can't link the function.
I could me making an error by needing to include the files but my understanding is if all the object files make it to the linker then all will be well (ie I just need the function declarations when making the object files which is what I have here).
With a "Blank project" it seems to compile all the cpp files even if they are never used so my case above works. (Although, it doesn't work for files in subfolders of src). Looks like its a "feature" of the "Hello world" project type but it's going to drive me crazy knowing there must be a way to get it to do this.
If anyone knows if it is possible to include this file without writing my own makefile (I'm not a makefile guru (yet!)), or let me know if this is not possible with autogen CDT that would be great.
Using MinGW GCC toolchain.
Thanks

getting the right compiler for C++

I am trying to learn c++ but most of the tutorials and books I have read or looked up teaches you this...
(I am assuming like most tutorials, they are teaching in the beginning to code either in win32 console or CLR console. In either case the following does not work.)
#include <iostream>
int main( )
{
std::cout << "Hello World\n";
return (0);
}
The IDE that i have is Visual C++ 2008 Express edition and they accept code like this
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
Or like this
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}
Honestly I do not no the difference in none of these and I am not sure if I should just download a older compiler so that it works. If someone can tell me what the difference in these are and where to go from there. That will help tremendously. Thanks
[Edited]
I am trying to do a simple hello world. But I get the error "system can not find path specified." I have screenshot that shows what the error looks like. It also is saying that my project is out of date when I clearly save the file before I build it. Apparently it can not find the executable file. I went to the debug fold and did not see any .exe file.
[Edited]
Ok, now When I try to build the project I get the following errors
1>------ Rebuild All started: Project: test, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'test', configuration 'Debug|Win32'
1>Compiling...
1>stdafx.cpp
1>Compiling...
1>test.cpp
1>c:\users\numerical25\desktop\test\test\test.cpp(1) : warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1> Add directive to 'stdafx.h' or rebuild precompiled header
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2653: 'std' : is not a class or namespace name
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2065: 'cout' : undeclared identifier
1>Build log was saved at "file://c:\Users\numerical25\Desktop\test\test\Debug\BuildLog.htm"
1>test - 2 error(s), 1 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
Here is the code I used
#include <iostream>
#include "stdafx.h"
int main( )
{
std::cout << "Hello World\n";
return (0);
}
Note: I tried using it with and without the #include "stdafx.h" When I tried it without the #include "stdafx.h", it said I might be missing it.
Not sure what you're asking. The first two examples you gave are valid C++ programs that should (will) compile with VC++. The third example is a C++/CLI program that must be compiled with the /CLR compiler switch (this is called Managed C++).
EDIT: Adding more specific information (from a comment below):
The first two examples are standard (native) C++ (albeit, the second example has MS-proprietary macros). They compile to native code. The third is C++/CLI (a "managed" extension to C++). It compiles to managed (.NET) code. Only the third snippet interacts with the .NET framework in any way. All three are absolutely buildable and runnable using the appropriate projects in VS 2008 (no command line necessary)!
Based on your latest update, it looks like you have probably modified some project properties and changed some paths. The app is building, but when you try to run it via VS (you should do this with <Ctrl>+F5, by the way), the executable cannot be found (there are several ways you could have messed this up by changing or playing with various settings).
Please note the difference between building and running. Building is the process of compiling and linking your source code. Running is launching the resulting executable. You seem to be confused between these (judging from your complaints about the "...out of date" dialog box). It is normal to get the "...out of date" dialog box if you try to run without rebuilding after you have made a change to the project (even if that change is saved). Just make sure you click "yes." You need to build the project before you can run it.
My recommendation is to completely delete your project and solution. Create a new empty project, as suggested elsewhere in this now-very-heavyweight thread, and don't modify any project settings. If this doesn't work, something is seriously wrong!
ANOTHER EDIT: Just for completion, since this question kept changing:
As others have already pointed out, your ultimate problem with the first snippet is the use of precompiled headers (PCH). PCH are turned on by default in new VS C++ projects. Their purpose is to speed compilation when many implementation files include the same set of headers -- preventing the compiler from having to parse the header files for each compilation unit.
You have three options:
(Recommended) Disable PCH -- Project Properties --> Configuration Properties --> C/C++ --> Precompiled Headers: Set Create/Use Precompiled Header to Not Using Precompiled Headers. (You don't need to do anything with the "stdafx.h" file or the #include for it.)
Place your commonly used #includes in "stdafx.h". In your case, you would put #include <iostream> in "stdafx.h".
Place your #includes after `#include "stdafx.h". Microsoft requires that the "stdafx.h" be the first included file in a compilation unit.
A minor point, which I don't see elsewhere in the answers: When using precompiled headers, such as your stdafx.h, you need to include them first. Change it to:
#include "stdafx.h"
#include <iostream>
and that should fix the errors about it.
Alternatively, it may be easier to simply switch off precompiled headers: Project > Properties > Configuration Properties > C/C++ > Precompiled Headers > Switch first option to "Not using precompiled headers". They can be useful for big projects but will just be awkward and annoying while you're learning, since they have extra rules (like this "must be included first") which aren't requirements of standard C++ .
The "difference" is pedantic. The latter are just Microsoft-specific entry points.
As you are learning C++, I recommend you use a compiler, and preferably an operating system that lets you focus on C++, and not the platform. For this I recommend g++, on an Linux distribution such as Ubuntu.
Try this tutorial, there are many others that are similar that quickly let you overcome being tied to the tools, and focus on C++.
int main();
int main(int argc, char* argv[]);
These are standard C++.
int _tmain(int argc, _TCHAR* argv[]);
int wmain(int argc, wchar_t* argv[]);
These are Windows-specific to handle Unicode arguments. See What is the difference between _tmain() and main() in C++?.
int main(array<System::String^>^ args);
This is not C++. This is C++/CLI.
For best portability, always use the first form.
Also,
int main(int argc, char** argv, char** envp);
This is a usually seen POSIX extension. Windows supports this form of main too. The envp means (pointer to) environment variables.
int main(int argc, char** argv, char** envp, char** apple);
This is for Mac only, obviously.
void main();
And this is wrong (nonstandard, some compilers (e.g. gcc) will reject it).
Visual C++ Express will compile the first example just fine.
However, you need to ensure the proper project settings:
Create an "Empty Project"
"Add a new item..." to the project via the "Project" menu. Select C++ (.cpp) file.
Copy/Paste code into new file
Press F5 to compile and run.
When "Project is out of date" dialog appears, press "Yes" (build the project)
The steps above ensure VC++ Express does not treat your file as a special Win32/Windows console application.
EDIT: added additional step 5 to prevent "Can't find..." dialog.
I managed to get the same dialog by making sure the exe file does not exist, and answering "No" to the build dialog. With a clean, empty project the exe file does not exist yet. It must be built first. If you answer "no" don't build it, VC++ dutifully does not build the exe and later complains about not being able to find it when it tries to run it later.
As STingRaySC pointed out, all three of your examples will compile in VC2008 express; it's just that examples 2 and 3 are what VC2008 Express will load up initially when you create a project (one of the examples is for Managed C++, as STingRaySC mentioned).
You can just delete the code in your second example (the C++ Win32 Console Application project) and paste in the more standard hello world program from your first example. It should compile and run just fine in VC2008 Express - it did for me.
I. Precompiled header
#include "stdafx.h"
is some kind of tricky stuff that comes your way.
If you create a project VC will normally switch on precompiled header.
This means that one header stdafx.h is created which is compiled only once.
This is done to speed up compile time in big environments. If you start C++
it will confuse you.
If you use stdafx.h it has to be the first header in the cpp file.
II. Unicode (Utf16)
int _tmain(int argc, _TCHAR* argv[])
Microsoft uses UTF16 to implement unicode strings.
This means you get two versions of main.
int main(int argc, char* argv[])
int main(int argc, wchar_t* argv[])
This is also confusing if you start.
To simply start you can use whatever editor you want.
Create the file.
Open a Visdual studio 2008 command prompt
cl main.cpp
main.exe
and you will see Hello World using code from books.
Afterwards try to understand some of the settings of VC.
But you should always use an empty project.
Else you have to care about stdafx, UNICODE, ...
_tmain with the _TCHAR argv is the way the C runtime allows you to handle unicode. If _UNICODE is defined, then _tmain will expand to wmain, and the _TCHAR argument will be of type wchar_t. If _UNICODE is not defined, then _tmain will expand to main, which will be the ANSI standard.
Therefore, so long as _UNICODE is not defined, the second snippet you posted is compliant with the standard.
Lots of waxing lyrical and some misinformation for you sift through already, but I suggest following wonsungi's advice. But to clarify his advice:
File->New->Project
Select Project Type "Win32", then Template "Win32 Console Project"
Give the project a name and location
OK
Select "Application Settings"
Check "Empty Project"
In the "Solution Explorer", right click the "Sources" folder, then Add->New Item
Type the name of the file, in the "name" box using a .cpp extension (you can ignore the templates if you wish).
Enter your code in the new file.
Woot!! I figured it out!!! Below is my original code
#include <iostream>
int main( )
{
std::cout << "Hello World\n";
return (0);
}
It was missing the header file #include "stdafx.h" . So I had to include it in there so I added it like this
#include <iostream>
#include "stdafx.h"
int main( )
{
std::cout << "Hello World\n";
return (0);
}
I was still getting an error like what you see in my edited question at the bottom. So What I did is I took #include and added it in my header file and then it worked!!!!!
Even the the books and alot of tutorials show to add #include to the actual cpp, for some reason in express edition I had to add it to header for it to work. I don't know WHY but it's a solution and now it works.
Download and install Dev-C++ on your system. If the code doesn't work on Visual C++, try it out on Dev-C++ (which uses the GCC compiler). You may get the same results or a different error message. Whenever you get an error message you don't understand, do a Internet search for the error message.