0
votes

I have 3 files; main.cpp (which contains main()), FileWriter.h, and FileWriter.cpp. I'm using g++ (version Debian 4.9.2-10) on Debian Jessie. My project contains .cpp files in '/root/dev/Practice/src/', and a single header (FileWriter.h) in '/root/dev/Practice/include/'. The compilation of the two object files works, but the linking to an executable complains about undefined reference to main(), although I do indeed have a seemingly valid one defined in 'main.cpp'.

Here's the output of my make file (which is in the root '/root/dev/Practice/' directory):

g++  -c -g -Wall  -o src/FileWriter.o src/FileWriter.cpp
g++  -c -g -Wall  -o src/main.o src/FileWriter.cpp
g++  src/FileWriter.o src/main.o -o bin/Practice
/usr/lib/gcc/i586-linux-gnu/4.9/../../../i386-linux-gnu/crt1.o: In function '_start'"
/build/glibc-J1NNmk/glibc-2.19/csu/../sysdeps/i386/start.S:111: undefined reference to 'main'
collect2: error: ls returned 1 exit status
Makefile:10: recipe for target 'bin/Practice' failed

Here's the contents of my main.cpp file:

#include <string>
#include <iostream>
#include "/root/dev/Practice/include/FileWriter.h"

int main() {
    std::cout << "Hello!" << std::endl;
    FileWriter * fw = new FileWriter("foofile");
    fw->AddLine("CRAP!");
    fw->AddLine("NO!");
    return 0;
}

My FileWriter.h:

#ifndef FILEWRITER_H_
#define FILEWRITER_H_

#include <string>
#include <iostream>

class FileWriter{
public:
    FileWriter(std::string);
     ~FileWriter();

    void AddLine(std::string);

private:
    std::string fileLocation;
    std::ofstream  *filestream;
};

#endif /* FILEWRITER_H_ */

...and my FileWriter.cpp:

#include "/root/dev/Practice/include/FileWriter.h"
#include <fstream>

// g++ linker error if 'inline' not included - why?
inline FileWriter::FileWriter(std::string fileName)
{
    this->fileLocation = fileName;
    const char * x = this->fileLocation.c_str();
    this->filestream = new std::ofstream();
    this->filestream->open(x, std::ios::out | std::ios::app);
}

inline FileWriter::~FileWriter()
{
    this->filestream->close();
}

inline void FileWriter::AddLine(std::string line)
{
    *this->filestream << line << std::endl;
}
2
Why the cursing? It can be frustrating but please refrain from doing so in public postsAndrew Li
@AndrewL he was preparing those words to say for when he realizes what the problem is...M.M
Whoops! LOL sorry. Edited to remove that.ErikJL
#include "/root/..." . if you're compiling as root, you are a brave fellow :)M.M
Brave, or just a dumb newbie who hasn't yet done anything to bad enough to make me create a user account :)ErikJL

2 Answers

2
votes

This line:

g++  -c -g -Wall  -o src/main.o src/FileWriter.cpp

should be:

g++  -c -g -Wall  -o src/main.o src/main.cpp
0
votes

I don't have access to this compiler, but in the past if you had main() in a C++ file you needed to "decorate" it with __cdecl

int __cdecl main() {

Try that? Or:

extern "C" int main() {