Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ learning header files. What's up with this semicolon? [closed]

I'm learning to make header files. Here's my code (three separate files)

//Main.cpp
#include <iostream>
#include "functions.h"
;
using namespace std;

int main()
{
    cout << multiply(3, 4) << endl;

    return 0;
}

//functions.cpp
int multiply(int x, int y)
{
    return x * y;
}

//functions.h
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_

int multiply(int x, int y)

#endif

The code compiles and runs, but the part that's bothering me is in Main.cpp. There's that semicolon under "functions.h" and above "using namespace."

I put it there because visual studio said it was expecting one, but I have no idea why. I don't see it in tutorials.

Sure, it works. But I don't like not knowing why it's there and that it shouldn't be.

like image 981
Dukkha Avatar asked Dec 29 '12 00:12

Dukkha


People also ask

Why #define is not ended with semicolon?

The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.

Can a program compile and run if we place a semicolon after a header file?

Because it's a preprocessor directive and preprocessor directives don't require semicolons: they're processed prior to compilation. It is just a syntax rule. Preprocessors don't need to have a semicolon at the end. #include is a directive for the preprocessor, the compiler never sees it.

Is semicolon a valid statement in C?

It is allowed by all relevant C/C++ standards, which is not a worse position than it not being allowed.

Why do we need to give a semicolon after a structure declaration?

You have to put the semicolon there so the compiler will know whether you declared any instances or not. This is a C compatibility thing. Doesn't even need the name or constituents: class { } waldo; is legal.


2 Answers

Because you miss one semicolon in functions.h

int multiply(int x, int y);
                          ^^^^ here

C++ separates statements with a semicolon.

The #include directive causes the contents of the "functions.h" file to be sent along with the contents of your file to the compiler. The result of this is that compilation errors caused by mistakes in header files are often reported in the code which includes them.(thx to Philipp)

like image 180
billz Avatar answered Sep 28 '22 00:09

billz


Since the C preprocessor knows nothing about the syntax of C at all - you can use it to put together emails, assembler source files or HTML if you like, it just puts all the source in one long file for the compiler to actually compile.

And you are missing a semicolon after int multiply(int x, int y) in "functions.h".

like image 44
Mats Petersson Avatar answered Sep 28 '22 00:09

Mats Petersson