I'm trying to access functions from another file for use inside my class definition:
// math.cpp
int Sum(int a, int b){
return (a + b);
}
// my_class.cpp
#include <math.cpp>
#include <my_class.h>
int ComputeSomething() {
...
return ::Sum(num1, num2);
}
Despite my best efforts, I can't get the compiler to spit out anything outside the likes of ::Sum has not been declared or Sum was not declared in this scope.
I'm trying to wrap my head around code organization in C++, any help appreciated.
It might be worth noting that I'm programming for Arduino.
To be able to access functions from a user-defined library, best divide that library into a .h (or .hpp) and a .cpp file. I understand you have actually done this, but tried various options – among them the inclusion of the .cpp file – for the sake of finding a solution.
Still, to ensure things work as expected, the declarations of functions and classes should go into the .h file, best protected by something like
#ifndef MY_H_FILE
#define MY_H_FILE
/* ..Declarations.. */
#endif
Then to include the .h file (I'll assume it's named my.h), either use
#include "my.h" // path relative to build directory
or
#include <my.h> // path relative to any of the include paths
The latter only works if my.h is found on an include path previously known to the compiler (e.g. what is specified using the -I command line option in GCC). The former works if the path to the .h file given is relative to the directory your are building from.
Finally, do not use a file name that can be confused with a system library (such as "math.h"), especially if you are using the <...> syntax, as the include path will definitely include the system library header files.
Have you followed the instructions given here?
User-created libraries as of version 0017 go in a subdirectory of your
default sketch directory. For example, on OSX, the new directory would
be ~/Documents/Arduino/libraries/. On Windows, it would be My
Documents\Arduino\libraries. To add your own library, create a new
directory in the libraries directory with the name of your library.
The folder should contain a C or C++ file with your code and a header
file with your function and variable declarations. It will then appear
in the Sketch | Import Library menu in the Arduino IDE.
Related
hi I'm new to c++ coding and I'm asking how to create and include a header file in a c++ program on Android, I've looked online on how to create the header file but whenever I include it with the complete path the compiler gives me a fatal error file not found message,whether I'm using termux emulator or CXXDROID IDE, I don't know why this is the case.
please help me because I'm stuck with this problem for days and I need to solve it in order for me to write meaningful programs as I'm using Programming Principles and Practice Using C++ Second Edition by Bjarne Stroustrup which uses a lot of user defined functions for the projects.
thanks in advance.
I've included the complete path of the header files and created the proper headers,
This is how to do it in Termux. (And any other system/app where you have a c++ compiler)
Let's assume you have these files in your project.
main.cpp lib.h
Inside lib.h you have this code
int myfunction(int agr1);
Then inside your main.c file you can reference it like this
// Note the quotes
// Local header files need to be
// referenced like this with their
// relative path
#include "lib.h"
int main(){
...
}
int myfunction(int arg1){
// Implement your function here
}
You can now access your functions defined in your lib.h file from your main.cpp file.
I need a tool (command line, script or source code) that extracts all inlcude files that are included by a source file (recursive) with given preprocessor defines and include paths. I want to know the ones that could be found and the one that doesn't. The include files that could be found shall be recursivly parsed.
I know about the
gcc -M /-MM
cl /P
solution, but this does not work for me. The preprocessor stops as soon as it could not open a file. But at this time I don't have the correct path for that files and just want the preprocessor to skip that file and to tell me that it could not include that file
Also the cinclude2dot.pl from here is not useful, because it seems not to consider given preprocessor defines.
Very useful is the include file hierarchy finder from CodeProject. It considers the preprocessor flags and shows me all include files. Even the includes that couldn't be opened. But it is written in MFC and I would have to reimplement this for the gcc what is not such simple because a lot of WinAPI stuff is used even inside the parser.
Thus, maybe some one knows another solution.
an simple example:
main.cpp
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <SharedClass.h>
#include "MyClass.h"
#ifdef FOO
#include <OptClass.h>
#endif
int main() {}
Right now I start the include extraction like (simplified):
.getAllIncludes main.cpp -I includepath1;includepath2 -PD FOO
and obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
OptClass.h
and for
.getAllIncludes main.cpp -I includepath1;includepath2
I'll obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
I know that the deafault header may also define some values. But in my case I don't need that information, because the project source code doesn't depend on any of that defines. If thus, I feed my tool with this preprocessor define...
In the end the tool works quite well. It runs recursivly over ALL necessary files and in the end I have all needed files for the project. Of course there are some small restrictions I don't want to name then all (e.g. every header of an source file name has the same name, ... ).
Using gcc -M <source_file>, the code is not compiled, it is only processed by the precompiler. And, any solution you may find needs to process the source using the precompiler, to be correct. Imagine that the source, somewhere, has the following snipset:
#ifdef USE_BOOST_SUPERLIB
# include <boost/superlib.hpp>
#endif
then without preprocessing you cannot know if <boost/superlib.hpp> is included.
I have "Hello World" code that uses function fhi from another hi.cpp file that has it's header.
Correct my if my understanding is wrong according following:
I can do include cpp file like #include "c:\c\hi.cpp" instead of using header without any problems except that fact that it looks more readable in header file.
If I include header like sample in my main program hi.h, must hi.h include hi.cpp, or it is done automatically according the same file name hi. I'm wondering how compiler knows where is function fhi body.
Is it possible to have different names for header and cpp files?
Programm:
#include "stdafx.h"
#include "c:\c\hi.h"
int _tmain(int argc, _TCHAR* argv[])
{
fhi(1);
return 0;
}
hi.h
#include <cstdlib>
#include <iostream>
int var;
int fhi(int f);
hi.cpp
#include <cstdlib>
#include <iostream>
int fhi(int f)
{
return 0;
}
must hi.h include hi.cpp
No. hi.h contains only declarations, that can be other by other .cpp files.
I'm wondering how compiler knows where is function fhi body.
It doesn't. You need to compile all *.cpp files into the object files. In your case, you will have two object files: program.o and hi.o. The linker can now take these two object files, and spit out the executable. References to other functions(in this case the actual definition of fhi(..)) is resolved in this stage.
Also why are you using absolute paths in #includes? It will break when you move the "c" directory around.
What normally happens is that the build system compiles the .cpp files into object files, that then are used to build the main executable. The means to tell this to the build system vary greatly.
One important point is that your hi.cpp must include hi.h. You should also put an include guard in hi.h, to make it safe to be included more than once in a translation unit.
I can do include cpp file like #include "c:\c\hi.cpp" instead of using
header without any problems except that fact that it looks more
readable in header file.
yes, you can do so but it is not recommended, one of the problems is encapsulation; you are not hiding implementation details. readability as you mention is also a concern, a header is easier to read since it clearly shows what methods are public.
If I include header like sample in my main program hi.h, must hi.h
include hi.cpp, or it is done automatically according the same file
name hi. I'm wondering how compiler knows where is function fhi body.
the header needs to be explicitly included in hi.cpp and any .cpp file that use the class defined in the header.
Is it possible to have different names for header and cpp files?
yes but it is not recommended, it makes it more difficult to find things.
as a general rule: think about that other programmers may want to look in your code so you need to structure it so that it is easy to read and understand as well as making it easier for you 2 years down the road to remember where things are.
In Visual Studio all CPP files included in the project will be compiled to produce OBJ files. These OBJ files will be linked together to form the EXE or DLL.
Including files are similar to pasting the contents of the file at that location. The only difference is that this pasting is done by the pre-compiler during compilation.
Finding out where a function body resides is done by the either the compiler if the function is inline or by the linker when the final binary is created.
First, if the header file is in the same directory as the source file including it, you can use just
#include "hi.h"
In other words, you don't have to use a full path. (See e.g. the inclusion of "stdafx.h".)
Second, in your header file you don't need to include other header files, unless you need types from those. In your header file you don't have anything that needed from the header files you include.
Third, you should protect header files header files from being included more than once in the same source file, this can be done with a so called include guard, on in some compiler via a special directive called #pragma once.
Fourth, in your header file you define a global variable var. This variable will then be defined in every source file you include the header file in, which will lead to errors. You need to declare the variable as extern:
extern int var;
Then in one source file you define the variable like you do now.
Fifth, you should never include source files in header file (with some special exceptions that you don't have to think about yet). Instead you add all source files to the project (I assume you are in MS VisualStudio) and it they will all be built and linked together automatically.
Sixth, since you seem to be using VisualC++, then you are probably using something called precompiled headers. This is something the compiler uses to speed up compilation. However, for this to work you have to include "stdafx.h" in all source files. That include actually has to be the first non-comment line in each source file.
I'm facing difficulty in understanding source and header files stuff.
Suppose
1)I have a source file(functions.cpp) which contains function named 'int add(int x,int y)' in the location /Users/xyz/Desktop/functions.cpp.
2)The header file(functions.h) which contain the declaration of the functions in source file(functions.cpp) is placed in /Users/xyz/Documents/function.h
3)Other source file(main.cpp) which contain 'main()' function need to call the 'add()' function defined in 'functions.cpp'.The source file 'main.cpp' is located in /Users/xyz/Downloads/main.cpp
I'm placing these files in different locations so that i can understand these concepts better.
So,how do i link function.cpp to main.cpp using functions.h.
#include " "
What is the path that i should use in the above include?
Also,it is my understanding that .h files provides the declaration of functions which are defined some where else and having a declaration is necessary for the compiler to call the functions which are defined in some other files or functions which are not defined yet. Is that right? Please correct me in case I'm wrong.
#include "functions.h"
Your code should not know about how you choose to arrange your source tree. To hard-code paths is to earn the hatred of whoever has to maintain this code (and that includes you six months from now).
Your build system -- whatever it is -- can deal with the paths. That could be as simple as:
g++ -I/Users/xyz/Documents -c functions.cpp
Your statement of how declarations/definitions work is basically correct.
Your first question has no answer. C++ does not define how header files are found, it's up to the compiler and they all do it a bit differently. If you want an answer you'll have to look up the details in the documentation of your compiler. I would recommend you put everything the same directory and stop worrying about it.
In the second part of your question, your understanding seems pretty good to me.
You should include in your main the exact path to your header file:
#include "/Users/xyz/Documents/function.h"
Hope this help.
Regards.
You include functions.h in functions.cpp and main.cpp using #include then you compile both main.cpp and functions.cpp. The linker then links the two resulting object files. Your inclusion of functions.h in main.cpp will allow you to call the functions from functions.h within your main.cpp file
As for paths of files, provided that you specify to your compiler the required paths in which to find your code you should be fine.
You can either use a full path
#include "/Users/xyz/Documents/function.h"
or a relative path (which is usually more preferable)
#include "../Documents/function.h"
Don't forget to specify full or relative paths to your .obj files when you are linking the final executable as well ;)
I want to import functions from another file in Microsoft Visual C++ 6.0. How can i do this? I have tried with this as follows:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#import <functions.cpp>
where functions.cpp is the file name from where I want to import the functions. But this gives an error: F:\CC++\Term Project\Dos Plotter\Functiom Plotter.cpp(6) : fatal error C1083: Cannot open type library file: 'Functions.cpp': No such file or directory
How can I solve this problem?
The #import directive is used with type libraries, often COM or .Net, not C++ source files. For complete details, see the MSDN page.
In order to include C++ functions from another file, you typically want to use the #include directive (details). This includes the code from the given file during compilation. Most often, you should include a header containing the function prototypes; it is possible to include code files, but not commonly needed or always safe.
To do this, you should provide two files, a header and a source file, for your functions.
The header will read something like:
#pragma once
void Function(int arg);
and the source:
#include "functions.hpp"
void Function(int arg) { ++arg; }
To use this in another file, you do:
#include "functions.hpp"
void OtherFunction()
{
Function(2);
}
You should also note that a header should typically be included only once. The MSVC-standard method of guaranteeing this is to add #pragma once to the beginning.
Edit: and to address the specific error you've posted, which applies to both #import and #include, the file you're attempting to include must be somewhere within the compiler's search path. In Visual Studio, you should add the necessary path to the project includes (this varies by version, but is typically under project properties -> compiler).
1) Did you mean functions.hpp? C/cpp files should not be #included unless you know very well what you're doing.
2) Add the location of the file to the custom include path in the project properties, or use the include "foo" format instead of include <foo>
3) Import is undefined in C. You need to separate prototypes and implementations, include-guard the prototypes file, and #include the prototypes file.
having the file functions.cpp on the same dir, use include "functions.cpp" instead
Name the file imported-function.hpp, and make sure that it is in the same dir. Or, you could link it to
Linux: /home/uname/appfolder/imported-function.hpp
Windows: C:\Username\uname\appfolder\imported-function.hpp
ChromeOS: /home/chronos/u-4e4342ea6b3b92244e7d4753922f0dc7125f4a1d/MyFiles/appfolder/imported-function.hpp