/r/cpp_questions

Photograph via snooOG

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


READ BEFORE POSTING


Tips for improving your chances of getting helpful answers:

  • thoroughly research for an answer first.
  • give your post a meaningful title, i.e., NOT "I have a C++ problem" but, e.g., "Problem with nested for loops"
  • be specific.
  • make your questions relevant to other readers.
  • if your post does not appear in the new queue, just send a message to the moderators.

Sort posts by OPEN or SOLVED

/r/cpp_questions

85,289 Subscribers

1

Issues Linking Static Library in C++ Game Engine Using Premake5

Hey everyone,

I'm working on a C++ game engine that is split into separate projects/compile units:

  • Core library: PFF (previously a DLL, now a StaticLib)
  • Editor: PFF_editor (ConsoleApp)
  • Helper program: 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!

0 Comments
2024/12/20
18:24 UTC

2

Negatively indexing a std::span

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.

17 Comments
2024/12/20
12:45 UTC

1

Android Dynamic Loading

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?

7 Comments
2024/12/20
11:06 UTC

0

A few questions about Premake...

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.

1 Comment
2024/12/20
05:41 UTC

0

How would I know? (User Research)

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?

3 Comments
2024/12/19
23:52 UTC

3

Mastering header files

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?

9 Comments
2024/12/19
22:39 UTC

9

Alternatives to std::find_if

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";
    }
   }

};
36 Comments
2024/12/19
18:41 UTC

2

constexpr member variable offset or pointer

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.

3 Comments
2024/12/19
17:57 UTC

1

I have 5 classes trying to access shared data, how to organize this?

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();
}
6 Comments
2024/12/19
14:14 UTC

0

tips to improve my code

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;
        }
    }









}
28 Comments
2024/12/19
13:00 UTC

3

Exporting enum from c++20 module

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.

3 Comments
2024/12/19
12:02 UTC

0

Learning C++ with ChatGPT / Google Gemini?

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.

4 Comments
2024/12/19
11:28 UTC

4

Is it safe to use reinterpret_cast in this case?

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;    
}
21 Comments
2024/12/19
10:44 UTC

0

I need help, I don't understand why my program closes automatically.

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.)

https://pastebin.com/9hVFK5hN

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).

51 Comments
2024/12/19
06:22 UTC

0

vscode unable to find iostream

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.

15 Comments
2024/12/19
06:18 UTC

1

Clangd help

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.

5 Comments
2024/12/19
03:15 UTC

0

Should I first learn C before C++ even when I got some concepts of C++ down?

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?

84 Comments
2024/12/18
23:48 UTC

1

Beginner: I dont seem to understand end-of-file

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.

12 Comments
2024/12/18
20:16 UTC

5

How do I ship a cross platform desktop application built with OpenGL and SDL2?

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.

3 Comments
2024/12/18
15:03 UTC

8

Alternatives to specializing a member function template from a class template?

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?

7 Comments
2024/12/18
14:55 UTC

2

Compiler cannot find Header files

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"
            ],
5 Comments
2024/12/18
14:01 UTC

4

How to make clangd work properly with standard library headers?

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.

7 Comments
2024/12/18
08:23 UTC

0

How would I make a coordinate system

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?

3 Comments
2024/12/18
00:18 UTC

1

Polymorphic allocators

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?

4 Comments
2024/12/18
00:05 UTC

2

filesystem::directory_iterator behaves differently on MacOS ?

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();
}
9 Comments
2024/12/17
23:39 UTC

4

What is the generator for Mingw64 gcc?

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

4 Comments
2024/12/17
23:38 UTC

0

I keep getting LNK1168 error for every project

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.

23 Comments
2024/12/17
21:18 UTC

6

Vector Classes: How does capacity of a vector grow to accommodate a addition of elements using "push_back( )" method?

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!

20 Comments
2024/12/17
20:07 UTC

1

how to debug undefined reference and variables error occurred after system and environment update?

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.

13 Comments
2024/12/17
19:20 UTC

4

Packaging via Conda

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)

9 Comments
2024/12/17
16:52 UTC

Back To Top