user3830784 user3830784 - 1 month ago 9
C++ Question

g++ error: expected unqualified-id before ')' token

I have a simple program that I am attempting to compile with g++ (ubuntu), trying to write my own makefile. The program goes as follows:

TestHello.cpp

#include "CLinHello.h"
int main(int argc, char **argv)
{
CLinHello hi = new CLinHello();
hi.sayHello();
}


CLinHello.h

#ifndef CLinHello
#define CLinHello

#include <string>
#include <iostream>

class CLinHello
{
public:
CLinHello(); //constructor
void sayHello();
};
#endif


CLinHello.cpp

#include "CLinHello.h"

CLinHello::CLinHello() {}

void CLinHello::sayHello(){
std::cout << "Hello from linux";
}


Lastly, my makefile:

# what compiler to use for Linux
CC=g++
# what flags to use
CFLAGS=-I
# looking for an "obj" directory where you currently are
OBJDIR=obj
# go up a directory, then look to "lib"
LIBDIR=lib
LIBS=-lm
#make program
testprogram: TestHello.cpp CLinHello.cpp
$(CC) -o TestHello TestHello.cpp CLinHello.cpp $(CFLAGS) $(LIBS)


Previously, when I had the "Hello from Linux" inside the main, I was able to get my program to compile without an issue, and I was then able to run my program from the command line. I am attempting to move the hello message to a separate class (so that I can eventually start doing something more complex there), and now when I attempt to build it, I am getting the following errors:

Error: expected unqualified-id before ')' token
CLinHello(); //constructor

error: an anonymous struct cannot have function members {

error: 'hi' was not declared in this scope
CLinHello hi = new CLinHello();


in reference to the class CLinHello. I have copy-pasted the code exactly as it is coming out of my program, and I haven't been able to figure out if I have a problem that I am missing in my c++ code or if I screwed up somehow with the construction of the makefile.

Answer

You are using the same identifier for your include guard and your class name. Don't do that!

That is, when the preprocessor sees

#define CLinHello

every instance of CLinHello after that gets replaced with an empty string, leaving nonsense like

class 
{
public:
  ();
  void sayHello();
};

to be compiled.