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.
Related
How can you list all externally functions/variables/types used within your program next to the header file #include they are defined in?
I am trying to achieve something like this...
#includes <blah.h> // getBlah, BLAH_CONST, isBlah
Why:
I am maintaining some large and old C (and C++) libraries with many dependencies on other libraries. Each file can contain upwards of 50+ #includes and identifying what header file a specific function belongs to is difficult to identify. Also, due to unique circumstances traditional IDE's do not work many with our operating system and/or size of includes path is massive.
Example:
// Currently
#include <teama_dateinfo_accessor.h>
#include <teamb_calendar_accessor.h>
bool isLeapYear(year: int) {
struct Year yearInfo = getYearInfo(year); // <- ?? where is this being defined
return yearInfo.isLeapYear;
}
bool isTaxMonth(month: int) {
struct Month monthInfo = lookUpMonth(month); // <- ?? where is this being defined
return monthInfor.areTaxesDue;
}
// Trying to Achieve
#include <teama_dateinfo_accessor.h> // getYearInfo, Year
#include <teamb_calendar_accessor.h> // lookUpMonth, Month
bool isLeapYear(year: int) {
struct Year yearInfo = getYearInfo(year);
return yearInfo.isLeapYear;
}
bool isTaxMonth(month: int) {
struct Month monthInfo = lookUpMonth(month);
return monthInfor.areTaxesDue;
}
Inspired by JavaScript & Python syntax for imports.
import { getYearInfo, Year } from 'teama_dateinfo_accessor';
from teamb_calendar_accessor import lookUpMonth, Month
This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.
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.
This is a silly question with something that must be an easy answer, but after hours of searching I cannot find the answer. What I need to do is have a pair of .cpp files, say main.cpp and help.cpp that have a variable, vars1 that they share and can both change the value and detect when that value has been changed. The way that would make sense to me is that I would simply declare the variable in a class inside a header file and include that header file in both .cpp files, but that doesn't seem to work.
Here is a copy of my code:
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "variables1.h"
using namespace std;
int main(){
variables1 vars1;
do {
cout << "Welcome\n If you need help, type 'yes' now\n";
cin.getline(vars1.input, 1024);
if (strcmp(vars1.input, "yes") == 0 || strcmp(vars1.input, "Yes") == 0){
vars1.helpvar = true;
cin.get();
}
else{
cout << "Okay then, glad that you know your way around\n";
}
cin.clear();
cout << "What would you like to do?\n";
cin.getline(vars1.input, 1024);
if (strcmp(vars1.input, "logon" ) == 0 ) {
}
} while (0 == 0);
}
help.cpp:
#include <iostream>
#include "variables1.h"
using namespace std;
int help(){
variables1 vars1;
do {
if (vars1.helpvar == true)
cout << "detecting";
} while (0 == 0);
}
variables1.h:
class variables1
{
public:
bool helpvar;
char input[1024];
};
Actually what you are doing is that for the main file and the help.cpp you are creating two different objects and are setting the helpvar variable for each of them separately. What you want is to have a single object that is used by both help.cpp and main to only modify a single instance of the helpvar variable.
Change your help function to be along the lines of
int help(const variables1& myHelpobject ){
if (myHelpobject.helpvar == true) {
cout << "detecting";
}
}
and then call the function in main as:
help(vars1)
What you were doing before was creating a separate, independent, help object.
Here we are creating the object in main and then passing a reference to it to the function.
The technique to use depends on the purpose of your variable.
If it is some sort of global parameters, that you have to use throughout all your code, the simplest is to define it as a global variable:
main file:
variables1 vars1; // outside all functions
int main(){
...
}
Either in variables1.h or in the other cpp files using the variable:
extern variables1 vars1; //outside all functions
However the code to initialise and maintain these variables in a should also be defined in the class. The constructor shall for example define the values by default, such as if help is enable or disabled.
If your variables are for communicating between different parts of your code, and especially if the main goal of some code is to process the content of these variables, then should better make this clear by passing the variable as parameter (by reference (&) if the communication is bidirectional, or by value).
There are 2 main issues with the code as posted:
int help() is never run
Something needs to call this function for it to run. There isn't anything doing that so regardless of the value of vars1.helpvar you are never going to see "detecting" output.
Consider adding a help.hpp with the definition of the function and call the function from main.
vars1.helpvar is not shared between main and int help()
Currently you have two instances of variables1 and helpvar is a member variable so each instance has a separate copy.
You could either:
Make helpvar a static member of variables1
Share once instance of variables1 between both main and help.
The use of static variables is more likely give design problem later so I'd favour option 2.
I am writing file conversion code from a proprietary file format to one more generic. My goal is to support multiple versions of the manufacturer's file format.
I have a multiple versions of the same proprietary headers. The headers define various structs which comprise the main file header (the file is simply a large header followed by raw data).
I need to read the first 4 bytes of the source file to determine the file version. The file version, in turn, tells me which version of the C-structs was used to create the file.
The issues are:
I can't modify the proprietary headers
The headers do not use namespaces or classes
There are a good handful of macros defined in the headers
Possible solutions:
Build different converter binaries for each file version type :-(
Inconvenient for both user and developer
Dynamically load libraries for each version
The converter is plugin-oriented, so there's already a lot of this happening
I have tried hacking with namespaces:
namespace version1 {
#include "version1.h"
}
namespace version2 {
#include "version2.h"
}
int main (void) {
version1::header *hdr = new version1::header;
return 0;
}
But this won't work because of include guards, and because there are multiple macros are redefined in each header.
Is there an elegant way to handle this?
You could use two different source files, together with a forward declaration:
// Forward declare in main.cpp:
namespace version1
{
struct header;
}
namespace version2
{
struct header;
}
// version1.cpp:
namespace version1
{
#include <version1.h>
}
version1::header* new_v1_header()
{
return new version1::header;
}
// other functions using `version1::header`
// version2.cpp:
namespace version2
{
#include <version2.h>
}
version2::header* new_v2_header()
{
return new version2::header;
}
// other functions using `version2::header`
Another alternative is to implement a wrapper class, which has a base-class that is just an empty shell:
class header_base
{
virtual int func1(char *stuff) = 0;
... many other virtual functions.
};
// Create implementation of header_v1 or header_v2:
header_base* make_header(unsigned int magic);
header_base.cpp:
#include "header_v1.h"
#include "header_v2.h"
header_base* make_header(unsigned int magic)
{
switch(magic)
{
case Magic_V1:
return new header_v1;
case Magic_V2:
return new header_v2;
default:
assert(0);
return 0;
}
}
and then implement, in two separate
in headerv1.h:
class header_v1 : public header_base
{
int func1(char *stuff);
...
};
header_v1.cpp:
#include "header1.h"
int header_v1::func1(char *stuff)
{
...
return 17;
}
And similar for header_v2.h and header_v2.cpp.