简体   繁体   中英

Create and include a header file with function declarations then a source file with definitions then another source file with calls to functions

So I am running through some C++ exercises courtesy of Bruce Eckel the idea here is that I am trying to create a header file with some function declarations then include that header file into a source file in which I create some definitions for those functions followed by finally creating a second source file that includes the header file and defines main () containing calls to all the previous functions.

The functions themselves are dummy functions containing only the name of the function so I know that they are working.

HEADER

#ifndef headerone
#define headerone 

int add(int x, int y);
void slap();
int sq(float z); 

#endif

SOURCEFILE WITH FUNCTION DEFINITIONS

#include "headerone.h"
#include <iostream> 
using namespace std;

int add (int x, int y){
    cout << "add, int x, int y return int" << endl;
}
void slap () {
    cout << "slap, no arguments, return void" << endl;
}

int sq(int z){
    cout << "sq, int z, return int" << endl;
}

SOURCEFILE 2 WITH FUNCTION CALLS

#include "headerone.h"
#include <iostream> 

int main (){
    add(2,3);
    sq(2);
    slap();
}

Edit: As listed in the comments below the function calls were missing argument lists which are now added and the new suite of errors for each function is along the lines of : undefined reference to 'add(int,int)' with the slap function additionally returning error: ld returned 1 exit status.

These:

add;
sq;
slap;

Are not function calls. Read the documentation, or a c++ book about the syntax: http://en.cppreference.com/w/cpp/language/operator_other#Built-in_function_call_operator

A function call expression, such as E(A1, A2, A3), consists of an expression that names the function, E, followed by a possibly empty list of expressions A1, A2, A3, ..., in parentheses .

Emphasis mine. Note the lack of parentheses in your code. Since you don't call the functions, there is no output.

I would also appreciate general tips about what to do when my code compiles correctly yet does not output (or work) as intended.

Enable all the warnings in your compiler. You should do that even if your program appears to work correctly. In this case, g++ for example, would warn you about statements that have no effect.

There are a few other bugs in your code:

add and sq return non void , but you forgot to return anything. Warnings would have notified you of this too. You didn't give a definition for int sq(float z) . You only defined it's overload int sq(int z) . So, if you did call sq , then your code would fail to link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM