0

program output: c:/program files/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:\Users\michal\AppData\Local\Temp\cczDvNoc.o:main.cpp:(.text+0x25): undefined reference to `openFile(std::basic_ifstream >&)' collect2.exe: error: ld returned 1 exit status

main.cpp:

#include <iostream>
#include <fstream>
#include <string>
#include "libs/libFiles.hpp"

int main()
{  
    std::ifstream myFile;
    openFile(myFile);

}

libFiles.cpp:

#include <fstream>
#include <string>
#include "libFiles.hpp"

void openFile(std::ifstream &myFile)
{

    std::string fileName;
    std::cout << "Enter name of the file to open: " << std::endl;
    std::cin >> fileName;
    do
    {
        myFile.open(fileName, std::ios::in);
        if (myFile.good() == true)
            std::cout << "Access granted\n";
        else
        {
            if (fileName.substr(fileName.find_last_of(".") + 1) == "txt")
            {
                std::cout << "Access denied\n";
                exit(0);
            }
            else
                fileName += ".txt";
        }
    } while (myFile.good() == false);
}

libFiles.hpp

#ifndef libFiles_hpp
#define libFiles_hpp
#include <iostream>
#include <fstream>

void openFile(std::ifstream &);
void readFile(std::ifstream &);

#endif
stackuser
  • 11
  • 5
  • [Code looks good to me](https://ideone.com/gzgrwQ). Make absolutely certain that libFiles.cpp has been built and the result's been passed to the linker. – user4581301 Mar 04 '20 at 17:53
  • The most likely reason for the error is that you forgot to include "libFiles.cpp" in your project's files. – R Sahu Mar 04 '20 at 17:53
  • How did you compile your code? – Behnam Arazkhani Mar 04 '20 at 17:55
  • @behnamarazkhani g++ main.cpp, when i compile libFiles im getting: c:/program files/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: c:/program files/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../libmingw32.a(main.o):(.text.startup+0xc0): undefined reference to `WinMain@16' collect2.exe: error: ld returned 1 exit status – stackuser Mar 04 '20 at 18:00
  • Use `g++ main.cpp libFiles.cpp` to compile and build your program. – R Sahu Mar 04 '20 at 18:05
  • @stackuser Do it like this: "g++ -c main.cpp libFiles.cpp" and then "g++ -o main.exe main.o libFiles.o" – Behnam Arazkhani Mar 04 '20 at 18:11
  • @RSahu thank you it works but what if i want to store my libFiles.hpp and libFiles.cpp in one directory and main.cpp in other? how to compile my program in this case? – stackuser Mar 04 '20 at 18:12
  • [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – R Sahu Mar 04 '20 at 18:15

0 Answers0