I am doing my first steps in IPhone developing. I want to use some c\c++ code but I can't find any reference of how it's done (will very appriciate if you can also refer me to your source when you give an answear)
I have a file called calc.h containing a "calculator" class with simple add and mult functions, I imported it exactly as I did with an Objective-C header file. What am I suppose to do now?
Whatever you were doing when you were coding just in C/C++.
For example:
#include "calc.h"
....
-(void) testCode { //obj-c
float x = 3;
float y = 8.0;
float sumOfTwo = sum(x, y);
}
Assuming that you have a function named sum in your header file similar with the one used above.
If you use standard extensions for the source files (e.g. .cpp / .c) you can simply build them without doing anything special.
If you use uncommon extensions you need to set the file type manually: In File → Get Info set File Type to sourcecode.cpp.cpp / sourcecode.c.c.
Note however that you can't use C++ in plain Objective-C (.m) files - if you want to do that you need to use Objective-C++ (.mm) instead.
For using C there is no such restriction as Objective-C is a superset of C - as with C++ you may need to watch out for uses of identifiers that are keywords in Objective-C though.
Related
I'm trying to use the Fortran template library as show here. I don't know if there's some needed installation in order to use it. Should I download the zip file ?
I created a file called task.F90_template as shown in the link and it contains:
T function task(self,ww,pas,cpt ,nb_element,cpt1,dt,dx,p_element,u_prime,u_prime_moins,u_prime_plus,&
&taux,grad_x_u,grad_t_u,grad_x_f,grad_t_f,ax_plus,ax_moins,ux_plus,ux_moins,sm,flux,tab0,tab)
T::self,ww,pas,cpt,nb_element,cpt1,dt,dx,p_element,u_prime,u_prime_moins,u_prime_plus,&
&taux,grad_x_u,grad_t_u,grad_x_f,grad_t_f,ax_plus,ax_moins,ux_plus,ux_moins,sm,flux,tab0,tab
end function task
I don't understand also where to instantiate the template manually using the C preprocessor
#define T integer
#include "task.F90_template"
#define T real
#include "task.F90_template"
I want also to ask about the extension of the file tasks.F90_template since it doesn't get automatically colored.
I used QT Desginer to create a finalversion_with_buttons.ui file,
later i converted it to finalversion_with_buttons.h file using the command
uic -o finalversion_with_buttons.h finalversion_with_buttons.ui
in command prompt.
I got to know that we cannot have a .cpp file and .h file contains everything we need, now how do i execute/run this .h file ?
Please check Qt Creator documentation e.g. "Creating a Qt Widget Based Application". It will give you some overview how to setup qmake/CMake project based on UI form files (aka Qt Widgets). The UI files itself may not be used standalone. It is only UI description.
It is always of benefit to create a ".pro" or ".cmake" file that contails all the stuff for the compilation of the project that has several benefits, even for
small programms.
I highly suggest reading through this sites, that helped me a lot in creating/compiling projects:
https://www.cprogramming.com/tutorial/makefiles.html
https://www.cprogramming.com/tutorial/makefiles_continued.html
This is what an automatic generated .pro file of the qt creator contains and I guess self explainatory:
QT += core gui multimedia multimediawidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
RESOURCES += \
mainwindow.qrc
If you are working with the qt designer part of the qt creator you got this xml .ui file and the easiest way to compile it would be just clicking on Build->Run or ctrl+R. If your .pro file looks like the above example with the right file names you should be good to go.
Actually it is possible to have just a c++ file and no header files - thats invented to make the projects more modular with classes - thats what c++ is all about compared with c. To quote Bjarne "Classes use to hide the ugly stuff" ..so you can read the programm and understand it without even knowing what the class files contain and do with your code with a proper reference, and you don't should have to care. And thats what qt does - hiding the ugly stuff you would have to do all by yourself in its classes so you can just call QPushButton and it works. (and many more benefits but to keep it simple, qt is just c++ classes)
This is an example for a class in the code without a header file:
[//example from here https://www.cprogramming.com/tutorial/lesson12.html][1]
#include <iostream>
using namespace std;
class Computer // Standard way of defining the class
{
public:
// This means that all of the functions below this(and any variables)
// are accessible to the rest of the program.
// NOTE: That is a colon, NOT a semicolon...
Computer();
// Constructor
~Computer();
// Destructor
void setspeed ( int p );
int readspeed();
protected:
// This means that all the variables under this, until a new type of
// restriction is placed, will only be accessible to other functions in the
// class. NOTE: That is a colon, NOT a semicolon...
int processorspeed;
};
// Do Not forget the trailing semi-colon
Computer::Computer()
{
//Constructors can accept arguments, but this one does not
processorspeed = 0;
}
Computer::~Computer()
{
//Destructors do not accept arguments
}
void Computer::setspeed ( int p )
{
// To define a function outside put the name of the class
// after the return type and then two colons, and then the name
// of the function.
processorspeed = p;
}
int Computer::readspeed()
{
// The two colons simply tell the compiler that the function is part
// of the class
return processorspeed;
}
int main()
{
Computer compute;
// To create an 'instance' of the class, simply treat it like you would
// a structure. (An instance is simply when you create an actual object
// from the class, as opposed to having the definition of the class)
compute.setspeed ( 100 );
// To call functions in the class, you put the name of the instance,
// a period, and then the function name.
cout<< compute.readspeed();
// See above note.
}
And a compiler doesn't see something else after the linker is done than that.
so
"I got to know that we cannot have a .cpp file and .h file contains
everything we need"
is not right because you can as seen in the example above. Just its not how c++ (or c with classes as it was called in the early days) should be used.
But to answer your question:
"how do i execute/run this .h file ?"
like said before, just use the qt creator and click on Run or crtl + R
(it is free for opensource and edu)
create a project file like exampled before and use qmake SampleProject.pro
in the command line. This will create a file by the name of “Makefile” in the project directory.
(like described here https://vitux.com/compiling-your-first-qt-program-in-ubuntu/
than issue the command make in the same directory
(also described here)
Create a make file like described in link 1 and 2.
Everything else is beyond the scope of this question like fiddling out the semantic for using gcc or g++
That being said, you can create QPushButtons and all the stuff with the qt creator or you can create push buttons just in the code without using the .ui xml - file
like described here:
https://www.bogotobogo.com/Qt/Qt5_LayoutNotUsingDesigner.php
But what all of the guys here highly suggest is: Get yourself a goot qt/c++ book or tutorial and learn the foundations about classes and qt and you gonna get to be a really good programmer in no time. I also hope deeply this post is able to clarify a lot of qt programming/compiling for you and you start to have fun and will create really nice applications :) Cheers
I have a program that uses plug-ins. As I'm in development, these plug-ins are currently just .h and .cpp files that I add or remove from my project before re-compiling, but eventually they will be libraries.
Each plug-in contains lists of data in vectors, and I need to dynamically load data from the plug-ins without knowing which plug-ins are present. For instance:
// plugin1.h
extern vector<int> plugin1Data;
// plugin2.h
extern vector<int> plugin2Data;
// main.cpp
vector<vector<int>> pluginDataList;
int CountPlugins () {
// Some function that counts how many plug-ins are present, got this bit covered ;)
}
int main() {
int numPlugins = CountPlugins();
for (int i = 0; i < numPlugins; i++) {
vector<int> newPluginData = /***WAY TO ADD PLUGIN DATA!!!***/;
pluginDataList.push_back(newPluginData);
}
}
I already access the names of each plugin present during my CountPlugins() function, and have a list of names, so my first gut feeling was to use the name from each plugin to create a variable name like:
vector<string> pluginNames = /*filled by CountPlugins*/;
string pluginDataName = pluginNames.at(i) + "Data";
// Use pluginDataName to locate plugin1Data or plugin2Data
That's something I've done before in c# when I used to mess around with unity, but I've read a few stackoverflow posts clearly stating that it's not possible in c++. It's also a fairly messy solution in C# anyway as far as I remember.
If each plugin was a class instead of just a group of vectors, I could access the specific data doing something like plugin2.data... but then I still need to be able to reference the object stored within each plugin, and that'll mean that when I get round to compiling the plugins as libraries, I'll always have to link to class declaration and definition, which isn't ideal (though not out of the question if it'll give a nicer solution over all).
I'm all out of ideas after that, any help you can offer will be most welcome!
Thanks! Pete
Why dont you save the data as JSON between the application and the plugins ? That way you will also allow other types of tech to plug-into your app, like javascript based plugins via an embedded version of v8 or c#/.net plugins via mono.'
So...I have a kernel mode component and a user mode component I'm putting together using the turnkey build environment of the NT DDK 7.1.0. The kernel component is all .c/.h/.rc files. The user mode component is .cpp/.c/.h/.rc files.
At first it seemed simplest to use build for both, as I saw you could modify the ./sources file of the user mode component to say something like:
TARGETNAME = MyUserModeComponent
TARGETTYPE = PROGRAM
UMTYPE = windows
UMENTRY = winmain
USE_MSVCRT = 1
That didn't seem to cause a problem and so I was pleased, until I tried to #include <string> (or <memory>, or whatever) Doesn't find that stuff:
error C1083: Cannot open include file: 'string': No such file or directory
Still, it's compiling the user mode piece with C++ language semantics. But how do I get the standard includes to work?
I don't technically need to use the DDK build tool for the user mode piece. I could make a visual studio solution. I'm a bit wary as I have bumped into other annoyances, like the fact that the DDK uses __stdcall instead of __cdecl by default... and there isn't any pragma or compiler switch to override this. You literally have to go into each declaration you care about and change it, assuming you have source to do so. :-/
I'm starting to wonder if this is just a fractal descent into "just because you CAN doesn't mean you SHOULD build user mode apps with the DDK. Here be dragons." So my question isn't just about this particular technical hurdle, but rather if I should abandon the idea of building a C++ user mode component with the DDK tools...just because the kernel component is pure C.
To build a user mode program with WINDDK you need to add some variables to your SOURCES file:
386_STDCALL=0 to use cdecl calling convention by default
USE_STL=1 to use STL
USE_NATIVE_EH=1 to add a support for exception handling
Everything else you already have.
I'll put my full SOURCES file for reference:
TARGETNAME = MyUserModeComponent
TARGETTYPE = PROGRAM
TARGETPATH = obj
UMTYPE = console
UMENTRY = main
USE_MSVCRT = 1
USE_NATIVE_EH=1
USE_STL=1
386_STDCALL=0
SOURCES= main.cpp
And main.cpp:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "bla bla bla!";
cout << s;
return 0;
}
Have fun!
Quick Answer
Abandon the idea of building user-mode components with DDK tools (although I find the concept fascinating :-P)
Your kernel mode component should be built separately from the user mode components as a matter of good practice.
Vague thoughts
Off the top of my head, and this really speaking from limited experience...there are a lot of subtle differences that can creep up if you try to mix the two together.
Using your own example of __cdecl vs __stdcall; You have two different calling conventions. _cdecl is all kernel stuff and all of the C++ methods are wrapped around in WINAPI (_stdcall) passing conventions and __stdcall will clean do auto stack clean up and expect frame pointers inserted all over the place. And if you by accident use compiler options to trigger a __fastcall, it would be a pain to debug.
You can definitely hack something together, but do you really want to keep track of that in your user-space code and build environment? UGH I say.
Unless you have very specific engineering reasons to mix the two environments, (and no a unified build experience is not a valid reason, because you can get that from a batch file called buildall.bat) I say use the separate toolchains.
I am trying to implement a Websocket Server. I am using the libwebsockets library.
ConnectionServer.c file has setup code for the library and main() function (I don't see anything of importance to post here.) This file includes 1 file for the received data callback called:
dmserver_callback.cpp.
This file then includes another file (my custom parser file) called:
data_parser.cpp.
This file then includes a file called definitions.h (the source of the problem).
Just bear with me; I understand that including files (daisy chaining; so to speak) probably isn't the best way to do this, and I more than likely should be using header files and such. One question I have is that is this particularly necessary?
To clarify, everything is working as intended until I try to add my own parsing mechanism.
The definitions.h file is as follows:
namespace EngineDefinitions {
enum Version {
Major = 1,
Minor = 2
}; //Version;
namespace Server {
enum enum_Server {
MAX_PLAYERS = 200,
MAX_TABLES = 42, // 3 tables per row.
MAX_TABLE_PLAYERS = 10,
GAME_PORT = 2040, //2042
MAX_PARAMS = 10
}; //Server;
};
namespace Login {
enum enum_Login {
USERNAME = 1,
PASSWORD = 2
}; //Login;
};
};
My error is:
definitions.h(1): error C2061: syntax error : identifier 'EngineDefinitions'
I loaded the exact same header in a new Win32 Console Project in Visual C++ 2010 Express and there it works. The only difference I see is the main file (where int main function resides).
In the project that the header file works is called:
ConectionServer.cpp (C++)
and the main project file that doesn't work is named:
ConnectionServer.c (C)
Does this have something to do with the file being compiled in C vs C++?
I think that the libwebsocket library is coded in C.
I can't recall if I created the project files in exactly the same manner or not.
P.S. Please let me know if there is any other information I can provide to help.
EDIT: I also realize you're not supposed to define types inside a header file (eg: enums).
I DID try to separate the source into .cpp and a header file using the extern enum
with no difference. In fact, got more errors (redefinitions) than I bargained for when trying to use them.
You need to understand that C++ and C are different languages. When you include the header file in a .cpp file, the compiler will try to compile the .h as C++ code. C++ supports namespaces, so everyone is happy. But when you try to include the .h from the .c file (which is what is actually happening if you follow the #includes), the compiler attempts to compile the .h as C code, yet fails because namespaces do not exist in C.
A common way to solve this problem is to use predefined macros. __cplusplus is defined when compiling as C++ code, and not defined when compiling as C code (obviously).
You could do this:
#ifdef __cplusplus
namespace EngineDefinitions {
#endif
enum Version {
Major = 1,
Minor = 2
}; //Version;
#ifdef __cplusplus
namespace Server {
#endif
enum enum_Server {
MAX_PLAYERS = 200,
MAX_TABLES = 42, // 3 tables per row.
MAX_TABLE_PLAYERS = 10,
GAME_PORT = 2040, //2042
MAX_PARAMS = 10
}; //Server;
#ifdef __cplusplus
};
#endif
#ifdef __cplusplus
namespace Login {
#endif
enum enum_Login {
USERNAME = 1,
PASSWORD = 2
}; //Login;
#ifdef __cplusplus
};
#endif
And of course, you lose the ability of namespaces in C anyways.
C does not have namespaces. For Real.
You cannot include a C++ file in a C file (unless it has been prepared for such use). If you then try to compile the C file, it'll try to compile even the C++ file as C. Instead, use separate compilation and header files.
Note that C does not understand namespaces.