VS Code on Mac Using C++ Debugger Not Working Properly - c++

I am having an odd issue. I am working in C++ and I have coderunner installed and the basic C/C++ extension from Microsoft, but I am having an issue with my debugger.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers{10,20,30,40,50};
for(int i = 0; i < numbers.size(); i++)
{
cout << numbers[i] << endl;
}
return 0;
}
At the moment hit Run Code it runes just fine displaying the output I was expecting, but when I run the debugger I choose g++. This is what displays in the debug console:
But I still have a problem listed as:
vec.cpp:7:24: error: expected ';' at end of declaration
vector<int> numbers{10,20,30,40,50};
^
;
1 error generated.
Build finished with error(s).
It seems to be running an older version of C++, but my configurations are as list
"C_Cpp_Runner.cCompilerPath": "clang",
"C_Cpp_Runner.cppCompilerPath": "clang++",
"C_Cpp_Runner.cppStandard": "c++17",
"C_Cpp_Runner.cStandard": "c17",
"C_Cpp_Runner.debuggerPath": "lldb",
"C_Cpp.default.cppStandard": "c++17",
"C_Cpp.default.cStandard": "c17",
// "liveServer.settings.CustomBrowser": "chrome",
"code-runner.executorMap":{
"cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
}
Any ideas on why this would happen? Really confused why it would execute in the debug console, but not in the debugger. My compilers, g++ and clang++ are both up to date.

If the compiler supports C++11 standards then vector<int> numbers{1, 2, 3}; can be used.
You should not get this error when you try the following usage:
std::vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
numbers.push_back(40);
numbers.push_back(50);
If you are using Clang compiler you should use the following command to compile:
clang++ -std=c++11 -stdlib=libc++ vec.cpp
You can learn about the clang++ command's options by reading the "Clang Command Line Reference".

Related

Compiling & building CPP using LLVM (Clang) on Windows10

I installed LLVM on a clear Windows 10 machine, without anything else. I installed the ARMCompiler6.14.1. I have a simple cpp for testing:
#include <stdio.h>
#include <iostream>
#include <vector>
int main(void) {
int counter = 0;
counter++;
printf("counter: %d", counter);
std::cout << std::endl;
printf("c++14 output");
std::cout << std::endl;
std::vector<int> vect{1, 2, 3, 4, 5};
for (auto & el : vect)
std::cout << "-" << el << std::endl;
return counter;
}
When I compile this with following line I get errors:
"C:\Program Files\LLVM\bin\clang++.exe" -MD -x c++ "C:\Test\test.cpp" -target armv7a-none-eabi "-IC:\Program Files\ARMCompiler.6.14.1\include"
The error is:
test.cpp 2:10:fatal error: 'iostream' file not found
When I compile this with following line I get an windows executable which runs:
"C:\Program Files\LLVM\bin\clang++.exe" -MD -x c++ "C:\Test\test.cpp"
Since I checked that in the LLVM\bin is anything from the developer.arm.com package (ARMcompiler 6.14.1), I think that I should get an a.out for ARM, but I do not. When I checked the generated object file with:
"C:\Program Files\LLVM\bin\llvm-objdump.exe" -f test.o
I get following:
test.o file format elf32-littlearm
arhitecture: arm
start adress: 0x00000000
which means the object file is correctly generated for ARM, but I did not get an executable a.out for ARM.
What am I missing? How should I compile a simple test program to get it cross-compiled for ARM? Should I get the binutil from GCC for the Clang to create ARM executables?

How to get rid of auto keyword error in c++11? [duplicate]

I am in the process of learning c++ and I'm using visual studio code for Mac. I use Code Runner to run my program. My problem is that when I use something from c++11 like "auto" for variable declaration, visual studio code gives me a warning like this, but if I try running it on Xcode or Eclipse it doesn't:
warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
for(auto y: nstrVec)
This is the program if it's necessary:
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <numeric>
#include <sstream>
int main(){
std::vector<std::string> nstrVec(10);
std::string str("I'm a string");
nstrVec[0] = str;
std::cout << str.at(0) << "\n";
std::cout << str.front() << " " << str.back() << "\n";
std::cout << "Length " << str.length() << "\n";
// copies all characters after the fourth
std::string str2(str, 4);
for(auto y: nstrVec)
if(y != "")
std::cout << y << "\n";
return 0;
}
And this is the c_cpp_proprerties.json file:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/System/Library/Frameworks/Kernel.framework/Versions/A/Headers"
],
"defines": [],
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
In VS Code:
File>>Preference>>Settings>>Extensions
find C_Cpp>Default:Cpp Standard drop down menu
set that to c++11
I spent so long today trying to figure out why I was getting this error and no where had the exact answer I required so I thought I'd post it here just in case I can save anyone the hassle.
If you're using code runner, look in user settings and set:
"code-runner.executorMap" : { "cpp" : "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt" }
The pertinent bit being "g++ -std=c++17".
This is providing of course you can compile your programme in shell using Daniel's solution above but not in VScode + and using code runner.
I had the same problem, but solved it using set vscode-user-settings <>
"clang.cxxflags": ["-std=c++14"]
I used this to solve my problem. Open your terminal
bash
echo "alias g++='g++ -std=c++17'" >> ~/.bashrc
source ~/.bashrc
zsh
echo "alias g++='g++ -std=c++17'" >> ~/.zshrc
source ~/.zshrc
For everyone who comes to this question to find a quick answer (like I did):
The following compiler command should compile your program main.cpp with the latest C++ standard (c++17) and should get rid of warning messages like the one described above:
g++ -std=c++17 -g main.cpp -o main
It is mentioned multiple times in the comments, but I think this question should have a regular answer.
If you're using CPH judge extension in VS add -std=c++11 in Cph › Language › Cpp: Args in extension settings
If you're using CPH, add this line to Cph >> Language >> Cpp: Args
-std=c++17
If it doesn't work for you, also go to File >> Preference >> Settings >>
Extensions >> C_Cpp >> Default:Cpp_Standard and set that to c++17
None of the answers here worked for me on Mac that were entirely within VSCode (I didn't want to modify my .zshrc file).
What did work though, was adding argument --std=c++20 for the clangd: Fallback Flags under Extensions > clangd, then restarting VSCode.
Fix for MAC + code runner.
Select Code -> Settings -> Settings
In the search prompt, seach "code-runner":
Click on "Edit settings.json"
Look for a field called "code-runner.executorMap" -> "cpp"
After g++, add the following to it " -std=c++17 ". In other words, the line should look something like this:
"cpp": "cd $dir && g++ -std=c++17 $fileName -o $fileNameWithoutExt &&
$dir$fileNameWithoutExt"
Close VSCode, and open it again.

C++ CodeBlocks upgrade to C++17 can't use std::filesystem

I need to be able to list the files in a directory, and so I'm trying to upgrade my C++ version in CodeBlocks to C++ 17 so i can use filesystem. To do this I followed the steps outlined at http://candcplusplus.com/enable-c17-in-code-blocks-mingw-gcc-for-all-version-with-pictures#:~:text=Enabling%20the%20C%2B%2B17,Create%20a%20project.
I didnt have to change much, CodeBlocks 20.03 and MinGW 8.1.0 are already installed. MinGW is already in my path from when I built wxWidgets. The Settings->Compiler...->Toolchain executables tab I didnt have to make any changes to, and appears in CodeBlocks as:
I also checked the box to use C++ 17 in compiler settings like so
I ran the test program on the website with the instructions and got "True!".
However when I change the basic test program to this, to try and use filesystem to read files in a directory, I get an error:
#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
const int i=90;
if constexpr (i) //'if constexpr' is part of C++17
{
cout << "True!";
}
else
{
cout<<"False" ;
}
std::string path = "../MagicProgCPP/files/debug images/";
for (const auto & entry : filesystem::directory_iterator(path))
{
cout << entry.path() << std::endl;
}
cin.get();
return 0;
}
The program stops building, opens the file fs_path.h and stops on this line:
#ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
if (__p.is_absolute()
|| (__p.has_root_name() && __p.root_name() != root_name())) <----- ******STOPS HERE
operator=(__p);
else
{
string_type __pathname;
if (__p.has_root_directory())
__pathname = root_name().native();
else if (has_filename() || (!has_root_directory() && is_absolute()))
__pathname = _M_pathname + preferred_separator;
__pathname += __p.relative_path().native(); // XXX is this right?
_M_pathname.swap(__pathname);
_M_split_cmpts();
}
#else
// Much simpler, as any path with root-name or root-dir is absolute.
if (__p.is_absolute())
operator=(__p);
else
{
if (has_filename() || (_M_type == _Type::_Root_name))
_M_pathname += preferred_separator;
_M_pathname += __p.native();
_M_split_cmpts();
}
#endif
return *this;
}
I get this error in the build log:
C:\Program Files\CodeBlocks\MinGW\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++\bits\fs_path.h|237|error: no match for 'operator!=' (operand types are 'std::filesystem::__cxx11::path' and 'std::filesystem::__cxx11::path')|
I'm prety confident the path exists as I entered it and there's files in it. The build log message suggests maybe I'm not using C++17? But when I click build, this is the line the program uses to build:
g++.exe -Wall -fexceptions -g -Wall -std=c++17 -c E:\testc17\main.cpp -o obj\Debug\main.o
What am I doing wrong? Thanks
The bug 78870 was fixed since 2018-07.
You should add to project options -> linker settings -> link libraries the following library: stdc++fs.
I tried to compile your code with MinGW gcc 8.1.0 (via CodeBlocks) and everything works well (clearly with another path, since I don't have the same directories as you).
You could also add a check on the existence of the search directory like this:
namespace fs = std::filesystem;
std::string mypath { "../MyDir" };
if(fs::exists(mypath))
{
for(const auto & entry : fs::directory_iterator(path))
{
cout << entry.path() << std::endl;
}
}
It appears that this exact problem is a known bug in mingw 8.1. The bug report is here: https://sourceforge.net/p/mingw-w64/bugs/737/
and has the error in the same location:
operator != is declared and defined in line 550, but referenced in line 237.
The problem is triggered by operator/= in line 233:
path& operator/=(const path& __p)
{
#ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
if (__p.is_absolute()
|| (__p.has_root_name() && __p.root_name() != root_name()))
operator=(__p);
else
{
string_type __pathname;
if (__p.has_root_directory())
__pathname = root_name().native();
else if (has_filename() || (!has_root_directory() && is_absolute()))
__pathname = _M_pathname + preferred_separator;
__pathname += __p.relative_path().native(); // XXX is this right?
_M_pathname.swap(__pathname);
_M_split_cmpts();
}
The bug report said this was fixed in master meaning you need to install a version of mingw with the fix applied. I believe the best method is to upgrade mingw to a version greater than 8.1
user4581301 commented above in the main question that the following link has instructions on how to get a mingw install: How to install MinGW-w64 and MSYS2?

How do I build and compile C++ in VSCode?

I recently installed VSCode to get started on C++. VSCode is installed, and I followed their guide to get started with C++: https://code.visualstudio.com/docs/cpp/config-msvc
Now when I go to build their mentioned program:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
this is what the terminal shows:
> Executing task: clang++ -std=c++17 -stdlib=libc++ helloworld.cpp -o helloworld.out --debug <
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
The terminal process terminated with exit code: 1
Terminal will be reused by tasks, press any key to close it.
I had installed XCode too as the VSCode website told to download it as a compiler for C++ in macOS.

c++ hello world throws Segmentation fault - MinGW, Netbeans

Set up MinGW and Netbeans. Only working withe othere IDE's and compilers in before. My machine is x64 win7x64. I'm not shure if I only installed the 32bit version of MinGW.
Compiling a simpel Helle World in x64 leeds to:
g++ -m64 -c -g -MMD -MP -MF "build/Debug/MinGW-Windows/main.o.d"
-o build/Debug/MinGW-Windows/main.o main.cpp
//Message: sorry, unimplemented: 64-bit mode not compiled in
The win32 Version compiles fine.
// ---
g++ -m32 -c -g -MMD -MP -MF "build/Debug/MinGW-Windows/main.o.d"
-o build/Debug/MinGW-Windows/main.o main.cpp
// Compiles without any error...
Starting the 32-Version it prints only one message and terminats withe a segmentation fault before returning from first std:cout. Using ftream, to make a file output same error occures.
The demo-Programm of netbeans "Welcome" throws the same exceptions.
#include <cstdlib>
#include <iostream> // EDIT! (worked at this post long time sry.)
using namespace std;
int main(int argc, char** argv) {
int i = 0; // for making shure, program is working before calling fs.open
std::cout << "hello world blubb" << endl; // this one shows up its message at consol.
//programm aborded.
std::cout << "Now again" << endl; // this on is never reached.
return 0;
}
Errormessages:
Signal received: SIGSEGV ( Segmentation fault )
For programm cppapplication_1 pid 7972
You may discard...
Errormessage windows:
cppapplication_1.exe does not work.
Where can I start my serach? Compiler? some dlls? Dependency Walker?
Thx for any comment =).
Cutton