I'm just getting started on my first ever C++ program and am pretty much just learning as I go. The program is supposed to have 3 different files, a header file (prog1.h), a prog1.cpp file (not sure the right terminology for this one) and a test file that includes main: to test our program (prog1_test.cpp).
Not asking for help on any of this (yet, I'm sure I'll be posting another question once I get into it), but figured you'd need to know what the program is supposed to do in order to understand my question. Our program is supposed to read in some numbers from a file and put these numbers into a 2D array. It's then supposed to assign characters to each number value and print the current array and the "picture" created with the characters. Then it will go through the array, making sure that each number doesn't differ in value from it's neighbors by more than 1, if it does, the program is to replace that number with the average of its neighboring values. The program will then print out this corrected array and "picture" created with the characters assigned to the corrected array.
I know that header files are supposed to include code that will be used across multiple files, but am having trouble figuring out what parts of my program need to go in this file. For example, would my code to open, read, and close the data file be included here, or no since the file is only being opened, read, and closed once?
Header files contain function and class declarations. These simply declare the name of the function, its return type, and its argument list. The .cpp file contains the definitions of these functions -- i.e. the actual implementation. The header file is visible to the rest of the program if you #include it in other files, but the implementation details are hidden in the .cpp file.
Anything declared/defined in the .cpp file that is not in the .h file is not visible to the rest of the program, so you can define internal variables, helper functions, etc. in the .cpp file and those implementation details will not be visible. An example of this is foo() in my example below.
A very rough sketch of your program would look like this:
In prog1.h:
#include <iostream> // and whatever other libraries you need to include
#define ARRAY_SIZE 100 // and other defines
// Function declarations
// Read number from file, return int
void read_number(int array[ARRAY_SIZE][ARRAY_SIZE]);
char assign_char(int n);
void print_array(int array[ARRAY_SIZE][ARRAY_SIZE]);
void neighbor_check(int array[ARRAY_SIZE][ARRAY_SIZE]);
In prog1.cpp:
// included headers, defines, and functions declared in prog1.h are visible
#include "prog1.h"
void read_number(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
char assign_char(int n) {
char c;
// implementation here
return c;
}
void print_array(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
void neighbor_check(int array[ARRAY_SIZE][ARRAY_SIZE]) {
// implementation here
}
// not visible to anything that #includes prog1.h
// since it is not declared in prog1.h
void foo() {
// implementation here
}
In prog1_test.cpp:
// included headers, defines, and functions declared in prog1.h are visible
#include "prog1.h"
// any other includes needed by main()
int main() {
int array[ARRAY_SIZE][ARRAY_SIZE];
read_number(array);
for (int i = 0; i < ARRAY_SIZE; i++) {
for (int j = 0; j < ARRAY_SIZE; j++) {
assign_char(array[i][j]);
}
}
neighbor_check(array);
print_array(array);
return 0;
}
The use of various header files, and code/implementation files separate and apart from the application file is done to promote maintainability and reuse of code. By collecting all related functions, variables and data structures in a single file, we prevent having to duplicate that code in every subsequent application we write.
Take for example your situation where you will be developing routines related to matrices or arrays. This scheme allows you to collect the common routines dealing with your arrays into a single file, say arrays.c. Now regardless of how many more programs you write, you have a common file that contain your array routines. Now if you write 5 more applications that need your array routines, you have them ready to go in arrays.c.
For maintainability, let's say you now have a more efficient way of handling input from a file to your array. Instead of having to go back and update the read_array function in 5 different application program files, you simply update the one read_array function in arrays.c and you have accomplished updating that routine for all applications that use it.
How does the header file fit in? In order to use your array functions in other applications, the applications need a common way of including the code to make it available for use. That is done by including your arrays.h header file in each application that needs it. OK, so what goes in arrays.h and what goes in arrays.c? Your header files will include the header files, function declarations, data structures and variables for your array routines that are necessary to implement the function definitions contained in arrays.c. That way any application that wishes to make user of your array routines need only include the line #include "arrays.h" at the beginning of its file to have access to your array functions contained in arrays.c
An example (in C) will help sort things out. Say you have several array functions that read lines in a text file into strings read_array, print the lines prn_array and then frees the memory used by the array and strings free_array. You have collected your array functions in array.c. (we know we will include array.h at the top.) So, for example:
#include "array.h"
char **read_array (char *filename)
{
char *buffer = NULL;
size_t len = 0;
ssize_t read;
char **array = NULL;
int cnt = 0;
FILE *fp;
fp = fopen (filename, "r"); //open file , read only
if (!fp) {
fprintf (stderr, "failed to open file for reading\n");
return NULL;
}
array = calloc (AMAX, sizeof (*array) * AMAX); /* allocate pointers, set NULL */
while ((read = getline (&buffer, &len, fp)) != -1) { /* read each line */
if (cnt == AMAX) {
fprintf (stderr, "Error: AMAX reached\n");
break;
/* you will realloc *array here in real life */
}
if (buffer[read-1] == '\n') { /* strip newline */
buffer[read-1] = 0;
read -= 1;
}
array[cnt] = strdup (buffer); /* copy buffer to array[cnt] */
cnt++; /* increment counter */
}
fclose (fp); /* close file stream (fp) */
return array;
}
void prn_array (char **array)
{
register int j = 0;
while (array[j]) {
printf (" array[%d]: %s\n", j, array[j]);
j++;
}
}
void free_array (char **array)
{
register int j = 0;
while (array[j]) { /* for each allocated string */
free (array[j]); /* free pointer to string */
j++;
}
free (array); /* free array */
}
Now let's create our header. We collect our function declarations along with any variables or data structures used and also include the system headers and any other included header files required by our functions in array.h:
#ifndef MY_ARRAY_H
#define MY_ARRAY_H 1
/* headers required for array.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define AMAX 100
/* function declaration */
char **read_array (char *filename);
void prn_array (char **array);
void free_array (char **array);
#endif /* MY_ARRAY_H */
Notice we have wrapped the contents of our header inside a test #ifndef MY_ARRAY_H which just asks the compiler if MY_ARRAY_H is defined yet, ifndef (if not defined), we let the compiler know that everything that follows our #define until we reach the end of the if statement #endif we are defining as MY_ARRAY_H so that if another file tries to include the same header -- the compiler knows it already has it and doesn't need to include it again. (not required, but we also give our define of MY_ARRAY_H the value 1)
So how do we put our custom header array.h and our custom functions for handling arrays in arrays.c to work for us? We write an application that makes use of the functions in arrays.c and to declare all the functions in arrays.c in our application, we simply include array.h in our application. (called application.c below):
#include <stdio.h>
#include "array.h" /* include array.h */
int main (int argc, char *argv[]) {
if (argc < 2) {
printf ("filename.csv please...\n");
return 1;
}
char **my_array = NULL; /* declare pointers */
my_array = read_array (argv[1]); /* call read_array */
prn_array (my_array); /* call prn_array */
free_array (my_array); /* call free_array */
return 0;
}
compile the application.c and array.c files:
gcc -Wall -Wextra -o application application.c array.c
run it on any short text file (less than 100 lines)
$ ./application input.txt
array[0]: 1. This is a simple input file with line numbers
array[1]: 2. for use with application showing the use of
array[2]: 3. header file: array.h
array[3]: 4. array functions defined in: array.c
array[4]: 5. (blank)
array[5]: 6. compiled with the following:
array[6]: 7. gcc -Wall -Wextra -o application application.c array.c
array[7]: 8. --------
array[8]: 9. Now you know!
Now you can see the benefit of creating a separate file holding the related functions, variables, and data structures we will use and creating a header file. We can reuse that code in any application we like simply by including the header file arrays.h in our application. We can update and maintain all our array functions in one place and updating our arrays.c will update all other applications that make use of that code.
I know I have left much out, but make sure you are solid on these concepts. They are fundamental to working with multiple source files and includes in C/C++.
Following basic things should appear in your header file.
class body with function declaration , data variable, constructor
and destructor declaration.
declaration of all functions in
class. Note: not a function body or definition.
inline
functions.
define
all library include header files. so you
need to add only one header file in you respective .c file of this
header file.
structures
ifndef block
forward declaration of
class if you need it some times.
doxygen comments for the
functions and classes and variables.
description of this file as
comment in top of you header file for doxygen.
etc...
Header file should not have any code.
Related
I have a C library that I want to use from within Octave. Following the tutorial, it seems straight forward: wrap the functions in C++ then mkoctfile them. The problem is: what if I want to have multiple functions definitions (wrappers) in a single source file?
In the mentioned tutorial it is stated
It should be noted that it is perfectly acceptable to have more than one DEFUN_DLD function in a source file. However, there must either be a symbolic link to the oct-file for each of the functions defined in the source code with the DEFUN_DLD macro or the autoload (Function Files) function should be used.
Then in the provided link:
Once Octave finds a file with a name that matches (the called function), the contents of the file are read. If it defines a single function, it is compiled and executed. See Script Files, for more information about how you can define more than one function in a single file.
In this second link, there is no info as to how to load a .oct file with multiple functions in it or how to generate multiple .oct files from a single source file. From what I've understood, the later is the correct approach. How can I do that?
The point of the second link is that you don't load a .oct file with multiple functions in it - at least not from octave's perspective. That's what the symlinks are for - you have symbols A, B, and C in there? Make A.oct, B.oct, and C.oct symbolic links that point at that file and you can use them as if each contained only the symbol you care about.
If you have multiple function definitions in a single oct file, you use autoload(). So if you have foo.oct which has functions foo and bar, then you do:
autoload ("bar", "path-to-foo.oct");
I'll start by clarifying the second quote-window in your question. This is not referring specifically to .oct defined functions. What this is implying is the difference between a canonical m-file defined function, and 'on-the-spot' functions defined directly in the console or as part of a script.
As for the first quote-window, when it comes to functions that are defined in .oct files, the situation is different. What it's saying is that you can create an .oct file that defines many functions, but in order to call these functions, there needs to be a file by the same name in your path. So if an .oct file defines functions "foo" and "bar", you need to have one copy of the .oct file called "foo.oct", and another (or, more realistically, as symbolic link to the original) renamed as "bar.oct".
Similarly, you can also define a "foo.m" and "bar.m" file in your workspace, which only contains the documentation for those functions, such that if you then do "help foo" or "help bar" you get the intended documentation out.
Alternatively, you can use autoload, as carandraug suggested.
Another possibility to generate a C to Octave interface is using SWIG which can generate a single .oct file with all your functions. Refer to here when using pointers and arrays.
Here is an example:
header
/* File: example.h */
int fact(int n);
int fact2(int n1, int n2);
void add(int *x, int *y, int *r);
source
/* File: example.c */
#include "example.h"
int fact(int n) {
if (n < 0){ /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
}
else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}
int fact2(int n1, int n2) {
return fact(n1)*fact(n2);
}
void add(int *x, int *y, int *r) {
*r = *x + *y;
}
interface
/* File example.i */
%module swigexample
%include "cpointer.i"
%{
#include "example.h"
%}
%pointer_functions(int, intp)
%include "example.h"
compile
swig -octave -o swigexample.cpp example.i
mkoctfile -I. -I/usr/include/octave-4.2.2/ -Iswiglib swigexample.cpp example.c
test
% File test.m
swigexample;
fact(5)
fact2(4,4)
% ==============
a = new_intp();
intp_assign(a, 37);
b = new_intp();
intp_assign(b, 22);
c = new_intp();
add(a,b,c);
r = intp_value(c);
delete_intp(a);
delete_intp(b);
delete_intp(c);
r
My intention is to include the LKH TSP Algorithm, which is written in C, into my C++ project.
LKH: http://www.akira.ruc.dk/~keld/research/LKH/
Sources: http://www.akira.ruc.dk/~keld/research/LKH/LKH-2.0.7.tgz
First of all I started to write a CMakeLists.txt to create a library that does not contain the LKHmain.c.
file(GLOB_RECURSE SOURCES SRC/*.c)
file(GLOB_RECURSE HEADERS SRC/INCLUDE/*.h)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/SRC/INCLUDE)
set(LIB_SOURCES ${SOURCES})
list(REMOVE_ITEM LIB_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/SRC/LKHmain.c)
add_library(lkh
${LIB_SOURCES}
)
target_link_libraries(lkh m)
After that I want to implement two function that uses the library.
The first one just reads a file of the TSPLib and copies the values into my own Map structure.
The second one should solve a TSP Problem by using my map structure without reading any file. (The program normally could only used by reading a file so this is a wrapper part)
Now my problem:
All the variables are defined in the LKH.h and used by all the implementations. So e.g.
LKH.h
int TraceLevel; /* Specifies the level of detail of the output
given during the solution process.
The value 0 signifies a minimum amount of
output. The higher the value is the more
information is given */
Node *FirstNode; /* First node in the list of nodes */
int InitialTourAlgorithm;
and now they are used in the *.c classes.
GreedyTour.c
#include "LKH.h"
GainType GreedyTour()
{
Node *From, *To, *First, *Last = 0, **Perm;
int Count, i;
double EntryTime = GetTime();
if (TraceLevel >= 1) {
if (InitialTourAlgorithm == BORUVKA)
printff("Boruvka = ");
else if (InitialTourAlgorithm == GREEDY)
printff("Greedy = ");
else if (InitialTourAlgorithm == NEAREST_NEIGHBOR)
printff("Nearest-Neighbor = ");
else if (InitialTourAlgorithm == QUICK_BORUVKA)
printff("Quick-Boruvka = ");
}
Cost = 0;
EdgesInFragments = 0;
From = FirstNode;
do {
From->Degree = 0;
From->Tail = From;
From->Mark = 0;
From->Next = From->Suc;
From->Pred = From->Suc = 0;
}
while ((From = From->Next) != FirstNode);
..........
..........
In this example the variables TraceLevel, InitialTourAlgorithm and FirstNode are used as global variables .
My problem: When I include the LKH.h to my class I have a lot of side effects. After executing a method, the global variables have changed.
I want to reset all of them to execute to next method without any previously set values.
I wrote several test cases and the gtest methods has strange effects which is in my opinion caused by the global variables behavior.
And here my wrapper files:
lkh.h
#include "model/map.h"
namespace ttp {
class LKHWrapper {
public:
MapPtr createMap(std::string);
int *calc(MapPtr map);
};
}
lkh.cpp
#include <fstream>
#include <limits>
#include "lkh.h"
extern "C"
{
#include "LKH.h"
#include "Genetic.h"
#include "Heap.h"
}
namespace ttp {
MapPtr LKHWrapper::createMap(std::string pathToFile) {
...
[change global variables]
...
return map;
}
int* LKHWrapper::calc(MapPtr map) {
...
[change global variables]
...
return BestTour
}
What is the easiest way to solve that problem and get a side effect free implementation of that two methods?
#Mason Watmough:
Yeah but the problem is I do not define them by myself. I have to use
extern "C"
{
#include "LKH.h"
#include "Genetic.h"
#include "Heap.h"
}
And that defines and declares the variables (see LKH.h at the C Program)
And there is no conflict or linking error!
The variables only exists once at the lkh.cpp by including the LKH.h.
The library liblkh.a does also not have this variables because they are ONLY defined at the LKH.h.
If your global variables are defined in your header file as well as your c programs, you will need to choose one or the other. either delete the global variable definitions from the c programs and put it all in the header files, or figure out how to properly put the header file into all different c programs. Conflicting variables between the header and the program is probably what caused this.
This question already has answers here:
error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere
(9 answers)
Closed 7 years ago.
You could have forgot to include problemclass.h from the file where you are using ProblemClass.
You could have misspelled the name of ProblemClass either in its own header file or in the place where you are using it. This can be
hard to spot if it is a capitalization error such as writing
Problemclass or problemClass instead of ProblemClass.
You could have copy-pasted your inclusion guard #defines from one header file to another and then forgot to change the defined names.
Then only the first of those two included header files would take
effect.
You could have placed ProblemClass in a namespace A, in which case you must refer to ProblemClass as A::ProblemClass if you are referring
to it from outside the namespace A.
You may be using templates and not expecting two-phase lookup to work the way it does.
You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old
version of that file under the misspelled name.
You could have made ProblemClass a macro that only gets defined after you include problemclass.h, in which case what you see as
ProblemClass gets replaced by something else by the macro
preprocessor.
You could have defined ProblemClass in a header file other than problemclass.h and then problemclass.h actually defines something
else.
The above was taken from another similar question, I found the points useful but none actually solved my problem, stated hereunder:
I'm creating a natural language processor for a robot, giving the software various objects to represent real world items in its environment (Blocks world for now), one of the objects defined in Block:
/*
* Block.h
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#ifndef BLOCK_HPP_
#define BLOCK_HPP_
#include "typedefinitions.h"
#include "dynamixel.h"
#include "BasicRobotFunctions.hpp"
class Block {
public:
bool grounded;
//TODO position is a deprecated variable, replace with distance from
//pos position;
int number;
int distance;
int object_brightness;
Block(BasicRobotFunctions basic);
virtual ~Block();
void setBrightness(int brightness);
void setGrounded(bool ground);
//void setPosition(int x, int y);
void setDistance(int number);
void setNumber(int number);
//pos getPosition();
int getNumber();
int getDistance();
bool getGrounded();
int getBrightness();
int lookAround(BasicRobotFunctions basic);
};
#endif /* BLOCK_H_ */
with source file:
/*
* Block.cpp
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#include "Block.hpp"
#define DEFAULT_PORTNUM 3 // COM3
#define DEFAULT_BAUDNUM 1 // 1Mbps
Block::Block(BasicRobotFunctions basic) {
grounded = false;
number = Block::lookAround(basic);
}
Block::~Block() {}
void Block::setGrounded(bool ground){
grounded = ground;
}
/*
void Block::setPosition(int x, int y){
position.x = x;
position.y = y;
}*/
void Block::setDistance(int dist){
distance = dist;
}
void Block::setNumber(int num){
number = num;
}
bool Block::getGrounded(){
return grounded;
}
/*
pos Block::getPosition(){
return position;
}*/
int Block::getNumber(){
return number;
}
int Block::getDistance(){
return distance;
}
int Block::getBrightness(){
return object_brightness;
}
//TODO Arrange function to incorporate Turn() in BasicRobotFunctions
int Block::lookAround(BasicRobotFunctions basic){
int num = 0;
dxl_initialize(DEFAULT_PORTNUM,DEFAULT_BAUDNUM);
for(int i = 0;i<360;i++){
dxl_write_word(11,32,-255);
dxl_write_word(11,30,200);
basic.Step(1);
dxl_write_word(11,32,255);
dxl_write_word(11,30,100);
if(dxl_read_byte(100,32) >= dxl_read_byte(100,52)){
num++;
}
}
dxl_terminate();
return num;
}
void Block::setBrightness(int bright){
object_brightness = bright;
}
I am however receiving the following compilation error from the constructor and from the turnAround(BasicRobotFunctions) method:
In file included from Robot.hpp:11,
from BasicRobotFunctions.hpp:12,
from main.cpp:8:
Block.hpp:23: error: expected `)' before 'basic'
Block.hpp:35: error: 'BasicRobotFunctions' has not been declared
make.exe: *** [main.o] Error 1
Having checked my other classes utilizing objects as variables I get the same error.
In response to the points in the quote:
- BasicRobotFunctions.hpp is included
- the class name is spelt the same in all different instances mentioning it
- I didn't copy paste any inclusion guard
- I didn't use any namespaces in the project
- Nor am I using any templates
- the file name isn't misspelled in my include
- I haven't defined any macros in the program
- I made sure every class was defined in its own header file
Is there any other issue my system could possibly have, any mistake I'm making or simply anything I'm doing which is bad programming practice here?
The cause of your problem:
You have a header file circular dependency problem.
main.cpp includes BasicRobotFunctions.hpp
which includes Robot.hpp
which includes Block.hpp
which includes BasicRobotFunctions.hpp.
If your header files are properly guarded against multiple inclusion (which it seems that they are), Block.hpp won't see the definitions of BasicRobotFunctions.hpp because it is already in the middle of including it.
How to spot the problem:
The source of this problem is apparent in the compilation error message and in your Block.hpp file.
The compiler is reporting an error in Block.hpp, and it is describing line by line how it got to that file via inclusions. The source to your Block.hpp file makes it clear that it is trying to include BasicRobotFunctions.hpp.
The fix:
In your case, you can modify your method signatures in Block.hpp to use a (perhaps constant) reference to the BasicRobotFunctions type, and then forward declare the type. This allows you to eliminate the dependency on the BasicRobotFunctions.hpp header file. (Block.cpp would likely need to include both Block.hpp and BasicRobotFunctions.hpp.)
//...
#include "typedefinitions.h"
#include "dynamixel.h"
class BasicRobotFunctions; // Forward declaration
//...
Block(const BasicRobotFunctions &basic);
//...
int lookAround(const BasicRobotFunctions &basic);
//...
You may be able to avoid this problem in the future by minimizing what headers are required to allow your header file to compile. This means your header file should:
Use forward declarations to types that are used.
Use references to forward declared types.
You can check that your header file has minimized its dependencies by making sure it compiles by itself. I accomplish this by including the header file first in a corresponding source file, and then make sure the source file compiles.
// Foo.cpp
#include "Foo.hpp"
//...
Well you can put a forward declaration before the class as
class BasicRobotFunctions;
class Block {
public:
bool grounded;
//TODO position is a ...
but this kind of error means that the #include "BasicRobotFunctions.hpp"
don't declare the BasicRobotFunctions. It's possible a trouble with code guards?
The circular inclusion can be solved using the forward declaration, putting correct guards in headers and moving some includes to source files.
I'm new to doing structs, so please bear with me if this turns out to be a dumb question. I have one header file and four .cpp files that all include it. I have a struct called ToDoLista and it has string nameIt and int DeadLine. Then I have the things whose type name I don't know that are like, the Soccer and DropOffMax and stuff.
ToDoLista Soccer, DropOffMax, CookDinner;
Soccer.DeadLine=6;
Soccer.nameIt="SOCCER";
//and so on, for a total of six, 3 ints and 3 strings definitions.
This struct seems to be finnicky if I try to move it around because if it's in the header it's included three times and it wont run due to 'multiply defined' whatever. If I put it in one of my three non-main cpp files, it seems that the struct won't work because some of it has to be defined in main(). So now it's in my main cpp file, but I have functions that use these values, and those functions are in my non-main cpp files, which as far as I know compile before the main one. To get around that, I put the struct declaration in the header, and the definitions in my main (I may have mis-worded that) AND THEN I say 'okay, run the function 'CheckItTwice'.
//MAIN
Soccer.DeadLine=6;
//and so on for all six, like before.
//ok, NOW run the fx.
CheckItTwice(Soccer.Deadline, Soccer.nameIt);
The issue here is that if I tell CheckItTwice to say, cout the string, or the int, it runs the program without errors, but returns nothing in the console where the cout should be, because apparently they haven't been defined yet, as far as the function is concerned. Why is this/do you know a way around this?
In order to avoid the "defined multiply" errors you need to define your struct in a header file, and put a #pragma once or #ifndef...etc block at the top. See this here.
Include the header file in any implementation (cpp) file you plan to use the struct in.
The line
ToDoLista Soccer, DropOffMax, CookDinner;
declares three instances of the struct ToDolista, called Soccer, DropOffMax, and CookDinner. They are not types, they are instances of a type, that type being ToDolista.
I can't comment on the contents of CheckItTwice() as you didn't provide them, but look here for guidance on using cout. You might want to consider passing the struct as one argument to this method, preferrably as a const reference.
Define the struct in your header and #include that header in the cpp files. In the header try adding
#pragma once
at the top of your header file. This is a Microsoft specific extension - documented here
The more portable version is to add
#ifndef _SOME_DEF_
#define _SOME_DEF_
struct ToDoLista {
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
}
#endif // _SOME_DEF_
Be sure to remove struct definition from the .cpp file.
I got this issue resolved using something I saw while searching desperately online: extern. it seems that if I put the declaraction in the header, the definition in a cpp, and then declare the object again in another cpp but with 'extern' before it, it works like a charm as far as keeping the values from the original definition.
Header.h
struct ToDoLista{
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
};
Side.cpp
ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
void CheckItTwice(int staytus, string name){
if(staytus==1){//not on the list
staytus==2;
cout << "hurry up and" << name << " okay?" << endl;
Main.cpp
extern ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
Pushups.namit = "Push Ups";
Pushups.status = 1;
Pushups.speed = 0;
Pushups.difficulty = 0;
Pushups.priority = 0;
Pushups.project = "Get Fit";
Pushups.deadline = 20131102;
CheckItTwice(Pushups.status,Pushups.namit);
This works for me, and I hope this 'answer' helps someone else.
Main idea:
I wrote a piece of code for dijkstra's algorithm and I'm dandy. However, I need to call the function (from a header file) in other codes and stuff. But I need to store the variables only when the function is called (so once the function is called it will return variables but won't return variable from previous calls). And I need to reference these variables other codes/files.
How I'm storing variables:
a structure that contains two vector.
My question:
Would it be best to create a .h file to store a structure and just change the variables there or is there a way to call variable from another function in another file and use it without having to worry about memory issues and whatnot?
Also... how would I set up my .h file for this dijkstra algorithm if my my int main takes no arguments?......
-Edit-
typedef struct
{
int a;
int b;
} STR;
STR Func()
{
STR str;
str.a = 5;
str.b = 6;
return str;
}
Basic model of my code. But I need to reference the structure and it's variable in another file with another function. However I get undefined reference to 'main' error when compiling so I added an int main() that calls Func(). Suggestions?
-edit dos-
Proposed fix
.h should include:
struct_name dijkstra(input variables)
.cpp should include:
#include "dijkstra.h"
typedef struct{
blah...
}struct_name;
struct_name dijkstra{
struct_name retval;
function def...
return retval;
}
main.cpp should include:
#include "dijkstra.h"
#include "dijkstra.cpp"
int main(){
initialize variables... blah
struct_name return_struct = dijkstra(input variables);
return 0;
}
Usually you would pass in all the input data the algorithm needs as input parameters, and return all the useful output data the algorithm creats as a return type. You could create a separate C++ struct or class if you need to bundle a few pieces of information together.
For data structures used internally by the algorithm - you would usually declare them only in the .cpp file, not the .h file. So, the user will not have any access / visibility of the internals (which is useful if you want to change how it works later).
So, the header file should just have the function declaration - with input arguments and output return type. All the algorithm code goes into the .cpp file, which includes the .h file. The header file is the 'interface' and the cpp file is the 'implementation', which we try to keep separate.
EDIT : (summarizing useful points from subsequent discussion)
This tutorial shows how the 2 .cpp files and one .h file fit together. Basically both .cpp files include the .h file. The .h file includes the declarations (for both the function type and for the struct type) but not the function definition :
www.learncpp.com/cpp-tutorial/19-header-files/
Since you are using g++, you can compile them into a single executable using :
g++ -o executable_name main.cpp dijkstra.cpp