/r/cpp_questions
a subreddit for c++ questions and answers
This is a subreddit for c++ questions with answers. For general discussion and news about c++ see r/cpp.
New to C++? Learn at learncpp.com
Prepare your question. Think it through. Hasty-sounding questions get hasty answers, or none at all. Read these guidelines for how to ask smart questions.
For learning books, check The Definitive C++ Book Guide and List
Flair your post as SOLVED if you got the help you were looking for! If you need help with flairs, check out ITEM 1 in our guidelines page.
Tips for improving your chances of getting helpful answers:
/r/cpp_questions
Hey everyone,
I'm working on a C++ game engine that is split into separate projects/compile units:
PFF
(previously a DLL, now a StaticLib)PFF_editor
(ConsoleApp)PFF_helper
(ConsoleApp)I'm using Premake5 as the build system.
Recently, I converted the core (PFF.lib
) from a DLL to a StaticLib due to architectural changes. However, after the conversion, the console apps (PFF_editor
and PFF_helper
) no longer link against the core library.
I'm not sure if this is an issue in my C++ code or something wrong with my Premake5 scripts.
You can find the repo here (on the dev
branch):
GitHub Repo - PFF Engine
If anyone has ideas, suggestions, or insights, I would really appreciate the help!
Thanks in advance!
If I have a vector of 10 elements and a std::span
of that vector over the last 5 elements, is it well defined to use indices -5 to -1 with that span to access the first 5 elements in the vector? My thinking is yes, it is well defined, as the underlying vector elements are not accessed out of bounds.
Hello everyone. I have a small question about dynamic loading and Android Native Development Kit (NDK).
Okay, so let's say I have an Android application that already has a library called liba.so . Now, I want to create an another library called libc.so that does dlopen to open liba.so, attempts to find a function Func() with dlsym and the mangled name of the function, then we use mprotect to modify the protections of the memory region, and then we call the function.
Now my issue is that every time when I call Func() with the pointer received, the application does not crash or something, instead, but the function does not get executed.
I have tested it out with both inline assembly and C++ function calling, both of them fails.
What I am doing wrong? Any ideas? What options do I have?
Disclaimer: By the way, what I am doing is only for educational purposes, I want to specify that I am not attempting any kind of illegal activity and that everything is being done inside my own application for learning purposes.
PS: Ask me anything if I skipped something.
Thanks. 😀
Update 1: I forgot to mention that I heard something about having to flush the CPU instructions cache, is it applicable here?
How do I include some files in a project if a Preprocessor Define is defined? For Example, say I have SSL define, if it's defined then include some crypto.cc and header files.
How exactly would I find out how someone was able to submit to C++ and how they joined organizations related?
Is there an obvious place I can look at their submissions? I keep hearing claims a certain user provided good work and is a long-term contributer, while others claim he uses AI slop.
No one has sources, so I want to check.
If this is the wrong place to ask this question, would you be a dear and cross post this or point me in the right direction?
As a programmer that has been at it for less than a year I often see myself jumping from header file to header file. I feel like other than the iostream I have not mastered any of them and even still I feel like it is member functions that come out of no where and are super useful. Does any one have any resources that are good guide for studying the STL? I know about cplusplus.com but any other websites,books,videos etc.. would be greatly appreciated. Also which header files are the most important one?
I implemented a very simple book and library implementation. In the library class there is a function to remove a book from a vector of books, when its corresponding ID is passed. While searching on how to do this, I came across std::find_if.
However it looks kinda unreadable to me due to the lambda function.
Is there an alternative to std::find_if
? Or should I get used to lambda functions?
Also could you suggest a way to enhance this so that some advanced concepts can be learned?
void remove_book(uint32_t id){
auto it = std::find_if(mBooks.begin(), mBooks.end(), [id](const Book& book) {
return book.getID() == id;
});
if (it != mBooks.end()) {
mBooks.erase(it); // Remove the book found at iterator `it`
std::cout << "Book with ID " << id << " removed.\n";
} else {
std::cout << "No book with ID " << id << " found.\n";
}
}
};
Is it possible to have some kind of constexpr construction for pointer to members (or offsets to the same)?
Code is a perhaps a 1000 words: https://godbolt.org/z/fhEe34bW7
I haven't done (really advanced) C++ since around 2017 came out, so I'm not 100% up to date on the wording, but do appreciate that reinterpret_cast (which offsetof morally does) is not allowed in constexpr stuff. It seems like it ought to be possible to make essentially a list of members of a struct along with their types for "manual reflection" by constructing an appropriate list by hand.
I've seen https://stackoverflow.com/questions/50080560/constexpr-offsetof-with-pointer-to-member-data and the linked http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0908r0.html but seems like there's no conclusion.
Maybe it is what it is, but both MSVC and GCC seem to be able to (mostly) do the their constexpr thing in practice, so maybe I'm just missing something.
Just playing around with ideas for now, so all pointers/input welcome.
Heres an image of the app for better imagination: https://imgur.com/a/VIMb598
So basically i did write a DataManager singleton class to handle image loading and holds the images in a vector.
UI components are checking the vector constantly and re-renders them to update the UI.
Its working really okay in a single thread. But im trying make it multithreaded to avoid freezing ui while loading images, while processing etc. Cant get out of segfaults, gonna lose my mind. Please guide me to properly load images in another thread. Here are the classes:
#include "DataManager.h"
DataManager::~DataManager() {
clearDirectory();
}
void DataManager::loadImage(const std::string &filePath){
cv::Mat mat = cv::imread(filePath);
Texture texture = Mat2Texture(mat);
size_t lastSlash = filePath.find_last_of("/\\");
std::string fileName = filePath.substr(lastSlash + 1);
imageList.push_back({fileName, mat, texture});
}
void DataManager::loadDirectory(const std::string &dirPath){
std::vector<std::string> filePaths;
for (const auto &entry : std::filesystem::directory_iterator(dirPath)) {
std::string filePath = entry.path().string();
filePaths.push_back(filePath);
}
std::sort(filePaths.begin(), filePaths.end());
for (auto &path : filePaths){
loadImage(path);
}
if (!imageList.empty()) {
selectedImage = imageList[0];
}
}
void DataManager::clearDirectory(){
for(auto &data : imageList){
UnloadTexture(data.texture);
}
imageList.clear();
}
#include "ImageBrowser.h"
void ImageBrowser::handleImageClick(const ImageData &clickedImage) {
std::cout << "Clicked image: " << clickedImage.fileName.c_str();
dataManager.selectedImage = clickedImage;
}
void ImageBrowser::update() {
if (!isOpen) return;
ImGui::Begin("Image Browser", &isOpen);
ImVec2 windowSize = ImGui::GetWindowSize();
float windowWidth = windowSize.x;
float columnWidth = 100.0f;
int columnCount = static_cast<int>(windowWidth / columnWidth);
if (columnCount < 1) columnCount = 1;
ImGui::SameLine();
if (ImGui::Button("Load Folder")) {
IGFD::FileDialogConfig config;
config.path = ".";
ImGuiFileDialog::Instance()->OpenDialog(
"ChooseFolderDlg",
"Choose Folder",
nullptr,
config
);
}
ImGui::SameLine();
if (ImGui::Button("Clear")){
dataManager.clearDirectory();
}
// Handle folder dialog
if (ImGuiFileDialog::Instance()->Display("ChooseFolderDlg")) {
if (ImGuiFileDialog::Instance()->IsOk()) {
std::string currentPath = ImGuiFileDialog::Instance()->GetCurrentPath();
dataManager.loadDirectory(currentPath);
}
ImGuiFileDialog::Instance()->Close();
}
// Display the images in a table
if (ImGui::BeginTable("Images", columnCount)) {
for (int index = 0; index < dataManager.imageList.size(); ++index) {
ImageData &img = dataManager.imageList[index];
ImGui::TableNextColumn();
if (img.texture.width != 0) {
// Display the texture and filename
float aspectRatio = static_cast<float>(img.texture.width) / img.texture.height;
// Make the image clickable
bool isClicked = false;
ImGui::PushID(index);
if (rlImGuiImageButtonSize("index", &img.texture, ImVec2(75,75))) {
isClicked = true;
}
ImGui::PopID();
if (isClicked) {
// Handle image click event
handleImageClick(img);
}
ImGui::Text("%s", img.fileName.c_str());
} else {
ImGui::Text("Loading");
}
}
ImGui::EndTable();
}
ImGui::End();
}
so i was on here a around 1 month ago when i just started, and i got a few great tips to improve with a pokemon "game" i chose that since its has alot of concepts in it, but is there a way to improve the code/ make it easier to read?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <string>
#include <file.hpp i dont want to include my full path in it>
int user_starter;
bool fileExists(const std::string& filename)
{
  std::ifstream file(filename);
  return file.good();
}
int main()
{
  // psudo random ods for shiny, hint for future me the randomness comes from the time since a computer cant do that shit
  srand(time(NULL));
  int shiny = (rand() % 4000) + 1;
  // blueprint for pokemons
  pokedex froakie;
  froakie.pokemon_id = 2133;
  froakie.speed = (rand() % 100) + 1;
  froakie.dmg = (rand() % 100) + 1;
  froakie.hp = (rand() % 100) + 1;
  froakie.shiny_lock = false;
  pokedex fennekin;
  fennekin.pokemon_id = 2131;
  fennekin.dmg = (rand() % 100) + 1;
  fennekin.speed = (rand() % 100) + 1;
  fennekin.hp = (rand() % 100) + 1;
  fennekin.shiny_lock = false;
  pokedex chespin;
  chespin.pokemon_id = 2343;
  chespin.dmg = (rand() % 100) + 1;
  chespin.hp = (rand() % 100) + 1;
  chespin.speed = (rand() % 100) + 1;
  chespin.shiny_lock = false;
  // uhh how did you forget the basics if you dont understand this go to https://www.youtube.com/@TheCherno and learn again and stop playing valorant dumbass
  std::cout << "ods: " << shiny << std::endl;
  std::cout << "pick a starter pokemon" << std::endl;
  std::cout << "1: for froakie " << std::endl << "2: for fennekin " << std::endl << "3: for chespin" << std::endl;
  std::cin >> user_starter;
  // logic for selecing a starter pokemon
  while(main)
  {
    if(user_starter == 1)
    {
      std::cout << "you picked froakie " << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl;
      if(shiny == 4000)
      { Â
        std::cout << "ods " << shiny << std::endl << "you got a shiny froakie" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: froakie" << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl << "shiny froakie";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: froakie" << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl << "normal froakie";
        savedata.close();
      }
    }
    else if(user_starter == 2)
    {
      std::cout << "you picked fennekin " << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl;
      if(shiny == 4000)
      {
        std::cout << "ods " << shiny << std::endl << "you got a shiny fennekin" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: fennekin" << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl << "shiny fennekin";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: fennekin" << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl << "normal fennekin";
        savedata.close();
      }
    }
    else if(user_starter == 3)
    {
      std::cout << "you picked chespin " << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl;
      if(shiny == 4000)
      {
        std::cout << "ods " << shiny << std::endl << "you got a shiny chespin"<< std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: chespin" << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl << "shiny chespin";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: chespin" << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl << "normal chespin";
        savedata.close();
      }
    }
    //if user was a dumbass and dident pick 1/2/3
    else if(user_starter != 1 || 2 || 3)
    {
      std::cout << "not a valid option" << std::endl;
    }
    else
    {
      std::cout << "loading save file" << std::endl;
    }
    std::string filename = "SaveData.txt";
    if(fileExists(filename))
    {std::cout << "save file is here" << std::endl << "loading progres...." << std::endl;
      break;
     Â
     Â
    }
    else
    {
      std::cout << "no save file" << std::endl;
      break;
    }
  }
}
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <string>
#include <C:\Users\xreri\Desktop\laptop\include\pokedex.hpp>
int user_starter;
bool fileExists(const std::string& filename)
{
  std::ifstream file(filename);
  return file.good();
}
int main()
{
  // psudo random ods for shiny, hint for future me the randomness comes from the time since a computer cant do that shit
  srand(time(NULL));
  int shiny = (rand() % 4000) + 1;
  // blueprint for pokemons
  pokedex froakie;
  froakie.pokemon_id = 2133;
  froakie.speed = (rand() % 100) + 1;
  froakie.dmg = (rand() % 100) + 1;
  froakie.hp = (rand() % 100) + 1;
  froakie.shiny_lock = false;
  pokedex fennekin;
  fennekin.pokemon_id = 2131;
  fennekin.dmg = (rand() % 100) + 1;
  fennekin.speed = (rand() % 100) + 1;
  fennekin.hp = (rand() % 100) + 1;
  fennekin.shiny_lock = false;
  pokedex chespin;
  chespin.pokemon_id = 2343;
  chespin.dmg = (rand() % 100) + 1;
  chespin.hp = (rand() % 100) + 1;
  chespin.speed = (rand() % 100) + 1;
  chespin.shiny_lock = false;
  // uhh how did you forget the basics if you dont understand this go to https://www.youtube.com/@TheCherno and learn again and stop playing valorant dumbass
  std::cout << "ods: " << shiny << std::endl;
  std::cout << "pick a starter pokemon" << std::endl;
  std::cout << "1: for froakie " << std::endl << "2: for fennekin " << std::endl << "3: for chespin" << std::endl;
  std::cin >> user_starter;
  // logic for selecing a starter pokemon
  while(main)
  {
    if(user_starter == 1)
    {
      std::cout << "you picked froakie " << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl;
      if(shiny == 4000)
      { Â
        std::cout << "ods " << shiny << std::endl << "you got a shiny froakie" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: froakie" << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl << "shiny froakie";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: froakie" << std::endl << "dmg: " << froakie.dmg << std::endl << "speed: " << froakie.speed << std::endl << "hp: " << froakie.hp << std::endl << "normal froakie";
        savedata.close();
      }
    }
    else if(user_starter == 2)
    {
      std::cout << "you picked fennekin " << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl;
      if(shiny == 4000)
      {
        std::cout << "ods " << shiny << std::endl << "you got a shiny fennekin" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: fennekin" << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl << "shiny fennekin";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: fennekin" << std::endl << "dmg: " << fennekin.dmg << std::endl << "speed: " << fennekin.speed << std::endl << "hp: " << fennekin.hp << std::endl << "normal fennekin";
        savedata.close();
      }
    }
    else if(user_starter == 3)
    {
      std::cout << "you picked chespin " << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl;
      if(shiny == 4000)
      {
        std::cout << "ods " << shiny << std::endl << "you got a shiny chespin"<< std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: chespin" << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl << "shiny chespin";
        savedata.close();
      }
      else
      {
        std::cout << "no shiny" << std::endl;
        // creating a txt file with the pokemons stats
        std::ofstream savedata ("SaveData.txt");
        savedata << "STARTER: chespin" << std::endl << "dmg: " << chespin.dmg << std::endl << "speed: " << chespin.speed << std::endl << "hp: " << chespin.hp << std::endl << "normal chespin";
        savedata.close();
      }
    }
    //if user was a dumbass and dident pick 1/2/3
    else if(user_starter != 1 || 2 || 3)
    {
      std::cout << "not a valid option" << std::endl;
    }
    else
    {
      std::cout << "loading save file" << std::endl;
    }
    std::string filename = "SaveData.txt";
    if(fileExists(filename))
    {std::cout << "save file is here" << std::endl << "loading progres...." << std::endl;
      break;
     Â
     Â
    }
    else
    {
      std::cout << "no save file" << std::endl;
      break;
    }
  }
}
What i´m basically doing is I'm attempting to create c++20 module wrapper for imgui. imgui has a lot of enums that I need to export. My issue is that for MSVC I need to write using enum [enum name] before I can use enums exported from module without their scope, but clang is happy to have exported enums without scope.
So in MSVC if I export enum I need to use it like this `ImGuiStyleVar_::ImGuiStyleVar_Alpha`, whereas clang is happy to compile `ImGuiStyleVar_Alpha` without scope.
Which one is correct (or is this undefined)? Or am I doing this completely wrong.
I created godbolt link here however it seems that it does not support CMake project for MSVC, but you can see the code.
Hello everyone. As a beginner, is it worth and should I be using AI tools like ChatGPT or Google Gemini to learn C++? I mean not using it for writing code, I want to use it for learning the basics and some other more advanced topics. I find it better because it can give you personalized responses, but I am not sure about the accuracy of the responses.
Thanks.
I want to do this because type "B" and "C" have different meanings (in terms of business context), but they share the same data members, and only the values of some of the fields are different. I can know the type in compile-time so I can have a template function to set fields that I need, and keep the original values of the other fields.
Of course, I can have a new copy of "B", memcpy "C" to "B", and set the fields, but I'm wondering if the following is safe or not, so that I may not need to do a memcpy, as the struct A itself can be large ( > 300 bytes) in my usecase, and I may just need to update a few of the data members and keep most of them unchanged.
It seems to be hacky, but I know what I'm doing so it should be fine.
#include <iostream>
struct A {
char message_id;
int b;
int c;
};
struct B : public A {
constexpr static auto id = 'B';
};
struct C : public A {
constexpr static auto id = 'C';
};
template<typename T>
void handle(T& t) {
t.message_id = T::id;
}
int main() {
C c;
B* bb = reinterpret_cast<B*>(&c);
handle(*bb);
std::cout << bb->message_id << '\n';
std::cout << c.message_id << '\n';
return 0;
}
I was creating a casino game, with basic uses, the issue is, in line 1215, the do while does not seem to work and skips the rest of the program, practically overriding the other functions, I do not know how or why it happens, please help me (Note: I admit that there are parts of code improvable at least, certain variables that can be declared all in a single line of code, abbreviated functions, etc.). I just want help to make the program work, not to make it optimal.)
If the code is in Spanish, it is because it is my original language, I am using a translator to make my understanding as good as possible, I would appreciate any help.
The present code is from line 1214 onwards, I don't know why it skips all the code that follows after line 1219 (after the marginint1, inside the do-while).
as the title states vscode can find any other file but the iostream and I do not know how to fix this. for reference I'm using a m1 mac if that matters, I'm wasting all my time figuring this out than actually coding lmao. please help.
edit: I deleted the command line tools and reinstalled them and that has seemed to fix the problem.
So I'm experiencing some clangd strangeness. std::expected just doesn't exist to it??? When I try to write anything with std::expected, the following error popos up:
No template named 'expected' in namespace 'std'
I'm running clangd on llvm18, and have set my compile commands as so: -std=c++23 -Wall -Werror -Wextra These are correctly passed onto clangd, that much I know. The issue also isn't with the compiler itself, as both gcc and clang compile the code just fine. Clangd however has different ideas and just shows nonexistent errors.
I have tried the following:
Using a newer version of llvm, I compiled both clangd and clang for the freshest patch off of github, no changes, still errors
Using libc++ instead of libstdc++, no changes
Manually setting feature flags in the toolchain, no changes
I really do not want to roll my own expected class, and short of trying to compile the freshes version of libc++ (which would have my cpu running red hot for hours, not ideal) as if maybe that would help, I have no idea what to do. Help please, and thank you.
I've heard that as a beginner that you should start with C before learning with C++. However, I already learned the introduction, flow control, functions, arrays, pointers, and some of classes and objects in C++. Should I still learn C before going back to C++ to better understand the concepts?
I recently started learning C++ and I cant seem to get this code to work because I end-of-file does not work as I expect it to:
#include <iostream>
int main() {
std::cout << "Enter any amount of numbers " << std::endl;
int num = 0, sum = 0;
while (std::cin >> num) {
sum += num;
}
std::cout << sum << std::endl;
return 0;
}
Whenever I type in several numbers and press enter, it does not terminate. I understand why this happens: I need an end-of-file. When I then input any non-integer, it terminates and outputs the sum up until the non-integer. I also understand why this happens. But whenever I try to write "(valid input) end-of-file", the program immediately terminates without even entering the while-loop. I tried everything that I can think of and searched the internet, but I cannot find an answer.
Recently, I've been having a lot of fun getting into gamedev with SDL2, OpenGL (with Glad) and C++. The main problem I'm facing is that my friends cannot easily run my programs without installing all of the dependencies and building from source. My goal is to create portable applications that run on Mac, Linux, and Windows regardless of whether or not they have SDL2 / Glad installed. I'm new to using C++ libraries, so I'm not sure what the best approach for this would be.
I run Windows and have used both wsl
and mingw
for C++ development. With both of these setups, I can just use a package manager to grab SDL2 and then import <SDL2/SDL.h>
, but of course that doesn't mean it will magically install for my friends.
My understanding is that I could choose to statically link SDL2 and will need to have a bunch of preprocessor directives to change how OpenGL is included and wether or not Glad is used. I am not sure that this is the correct approach and have seen people advise against statically linking SDL2. I don't need everything to be a single executable (I'm happy to just send over a zip file that also has SDL2.dll in it, for example) but do want to make sure they don't have to run any commands or install anything. I think the better approach is to start setting up my projects to have src
, lib
, and include
directories and put everything in there but have seen conflicting setup guides for this.
How can I set up my development enviroment / build scripts to accomplish this?
Apologies for the long-winded newbie question.
Apparently if you have a class template like this:
template <typename T>
class ClassTemplate {
public:
...
template <typename Q>
void functionTemplate(Q argument);
...
};
C++-20 still has no way to provide default specializations for the member function template, unlike how it would were the class not itself a template. One alternative is to use constexpr and std::is_same:
template <typename Q>
void functionTemplate(Q argument)
{
if consexpr(std::is_same(Q, SomeType)) {
...
} else if constexpr(std::is_same(Q, SomeOtherType)) {
...
} ...
are there any better options?
Hello, I am pretty new to sorting my files out since I usually only have one file for my code, since each project hasn't needed more than one. But I want to get into the habit of sorting the files, so I have tried but I cannot seem to get the project compiled. I am simply learning how to use SFML, and I have 1 header file, but the compiler can't seem to find it, any help is appreciated, thanks.
I am linking the file by going:
#include <Animation.h>
My makefile is:
all: compile link
compile:
  g++ -c "Source Files/main.cpp" "Source Files/Animation.cpp" -I"C:\Users\snosh\OneDrive\Documents\Libraries\SFML-2.6.2\include" -DSFML_STATIC
link:
  g++ main.o -o main -L"C:\Users\snosh\OneDrive\Documents\Libraries\SFML-2.6.2\lib"  -lsfml-graphics-s -lsfml-window-s -lsfml-system-s -lopengl32 -lfreetype -lwinmm -lgdi32 -lsfml-main
clean:
  del -f main *.o
And the include paths:
"includePath": [
        "${workspaceFolder}/**",
        "${workspaceFolder}/Header Files",
        "C:/Users/snosh/OneDrive/Documents/Libraries/SFML-2.6.2/include"
      ],
When I enable clangd, it will start to complain about the headers not being used directly, while also highlighting members that are declared in those specific headers as erroneous.
I have already exported compile commands in cmake. In CMakeLists.txt, both target property CXX_STANDARD and CXX_STANDARD_REQUIRED have been set to C++17.
If it's important, I have both MSYS2 GCC and MS VC++ installed. I'm using MSYS2 GCC to compile it, but clangd's path points to MSVC++'s standard library.
Not sure if it's actually significant, though, because including stuff from include/ also results in the same error.
Edit: The error was fixed by installing clangd through MSYS2's clang-tools-extra package.
I want to make just a small cpp project of a coordinate system entirely in the console an ex of this would be
OOOOO OOOOO OOOOO OXOOO OOOOO X = 1, -1
How would I do this in raw cpp?
What are some compelling reasons to use std::memory_resources and more importantly compose them. What are some useful allocators that can be derived from using them. I understand what each resource does individually but struggle to understand when we might want to compose multiple together and how to use them in a coherent program. Imagine the following scenario. Let's say we are very pedantic and we really want to minimize memory allocations in a small C++ server. Let's assume we will be dealing with small JSON object and let's say the server will use some sort of a thread pool. What I'd like to be able to specify through the memory resources would be something like this: Hey runtime can you please create me N unsunchronized pools one for each thread. Then can we please preallocate X bytes of memory and each pool will get memory from it's buffer. That's maybe one use case. Another could be imagine we have chain of async operations in a session object. At the start of the chain we need some memory and at the end we simply want to reset that memory block so that we can use it for the next operation. Well we don't really have a resource for that monotonic resources have to be freed when done with. I feel like the STL has do e a great job with the pmr but I just wish there were a little more examples on how and why these resources can be composed. What are some use cases you have had for them and how did you implement the allocation strategies?
This is the code im using to load some images into std::vector
On Windows the images are ordered by filename, but on MacOS vector looks completely randomized.
Is there anything wrong with the code ?
DataManager::~DataManager() {
clearDirectory();
}
void DataManager::loadImage(const std::string &filePath){
cv::Mat mat = cv::imread(filePath);
Texture texture = Mat2Texture(mat);
size_t lastSlash = filePath.find_last_of("/\\");
std::string fileName = filePath.substr(lastSlash + 1);
imageList.push_back({fileName, mat, texture});
}
void DataManager::loadDirectory(const std::string &dirPath){
for (const auto &entry : std::filesystem::directory_iterator(dirPath)) {
std::string filePath = entry.path().string();
loadImage(filePath);
}
if (!imageList.empty()) {
selectedImage = imageList[0];
}
}
void DataManager::clearDirectory(){
for(auto &data : imageList){
UnloadTexture(data.texture);
}
imageList.clear();
}
I have installed the ucrt64 environment mingw-w64 GCC using MSYS2. Now i would like to use cmake with it.
On cmake I've seen both "MinGW makefiles" and "Unix makefiles" being used as generator. What is the difference between them and which one should I choose? I am still somewhat confused by these different build file options.
Edit: Thanks for the answers! I'll check out ninja
Every project I open and try to run gets LNK1168 no matter if it was a new project or an old one.
I've tried repair. I've tried uninstalling and reinstalling. I've tried checking "Automatically close the console when debugging stops". I've tried excluding it from the anti-virus I'm using and absolutely nothing worked.
anyone has a solution? The problem is for all projects in Visual Studio 2022, and it suddenly happened it was working perfectly fine the day before.
Hi r/cpp,
I'm learning about arrays and came across the vector class. I was working with this sample code below:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
  //Declare and init objects
  vector<int> A(5);       //An array A of capacity 5
  //Print
  cout << "---------- BEFORE ---------------" << endl;
  cout << "capacity = " << A.capacity() << endl;
  cout << "size = " << A.size() << endl;
 Â
  //Add 2 additional elemetns to the end of A
  A.push_back(10);
  A.push_back(20);
  //Print
  cout << "---------- AFTER ---------------" << endl;
  cout << "capacity = " << A.capacity() << endl;
  cout << "size = " << A.size() << endl;
  //Exit
  return 0;
}
After running this code this was my output:
--------------------------------------------------------
------- BEFORE -------
capacity = 5
size = 5
------- AFTER -------
capacity = 10
size = 7
-------------------------------------------------------
So, I wanted to understand how the capacity is determined...based on my testing (added 4 more elements (not seen here) so size was 11 and the capacity was 20) it seems that it incremented by 10 each time the size equals the capacity. Where can I find the code for the vector class that determines this? I would like to confirm this is how the class operates .
Thanks in advance!
I'm giving a wild try here. So basically my code was fine and working until today when my "make -j" crashes due to undefined variables and reference. I'm on a shared server and I noticed that something has changed on the machine, e.g., my cmake points to something irrelevant and I need to manually fix my PATH variable to use cmake. So someone did something to the machine and my code breaks. Are there suggestions on how to deal with these?
edit:
And I feel the error may have to do with gcc or cmake version or other things because of the following error:
../third-party/libcommon/include/lib/common/filesystem.hpp:78:1: error: ‘uint64_t’ does not name a type
78 | uint64_t file_size(const std::string& path);
| ^~~~~~~~
../third-party/libcommon/include/lib/common/filesystem.hpp:1:1: note: ‘uint64_t’ is defined in header ‘<cstdint>’; did you forget to ‘#include <cstdint>’?
+++ |+#include <cstdint>
Originally I do not need to include <cstdint> separately but now there is a need.
edit2: thanks for all the help. I have modified the files to include the headers and errors are resolved. I still have a long way to go here. I did not realize it was this easy to be fixed. Again I learned another important lesson.
I am new to C++ development. I am trying to build and distribute a command line tool that is targeted towards bioinformaticians and would like to do so with conda.
In the current state of the project, one could clone the repo and build the tool via cmake. One could install it via homebrew for macos as well but I am sure it is a bit janky.
In the past few days I realised I was out of my depth trying to wrangle with anaconda compilers, resolve dependencies and cross compile properly. But that is the way I would like to go with this project and would be a great learning experience.
Could someone with experience in this department shed some light on the topic by providing some resources or pointing to similar projects? I am definitely not providing enough information so I would be happy to do that as well.
Thanks :)
(TLDR: building and packaging c++ app with conda for multiple platforms)