How to use SQLite in C++ program using Code::Blocks? - c++

I'm a complete beginner with Code::Blocks and SQLite, and have some basic knowledge with C++. I'm currently using Ubuntu 11.04.
I have downloaded SQLite Amalgamation here. When I extracted the zip file, there are four files inside: shell.c, sqlite3.c, sqlite3.h, and sqlite3ext.h. If I simply add those files to a (for example) a console project, it gives out an error: the .c's of the downloaded sqlite each have their own main function. Removing those from the project, the errors are gone and I can call #include "sqlite3.h". I am trying to follow this, and tried the first two lines of code from here and it gives out an error: undefined reference to sqlite3_open.
I think adding those .h's directly to a console project isn't the right way to use it, though I'm not sure.
How exactly should I use those? What should I do to use those for my C++ program?
Any help is greatly appreciated. :)
EDIT: I also tried to create a .a file of those sqlite files by following this. When I try it, it gives out an error: cannot find -lsqlite.

I got it! Though there was something that I did that caused problems.. I forget to remove the .a file that I added at Project > Build Options > Linker Settings earlier, which caused problems..
Here are the steps I made to add SQLite: (for those that might have the same problems)
Copy the files extracted from the SQLite Amalgamation to the directory of the project.
Add the sqlite files (Project > Add Files) EXCEPT the shell.c (it is the one that causes the multiple function error)
Compile it (Yes, a simple Ctrl+f9).
here are errors: undefined reference to pthread_mutexattr..... These are fixed by going to Project > Build Options > Highlight 'the Project Name' above Debug and Release at the top left corner > Linker settings, and adding "-lpthread" (without quotes) to Other linker options:.
Some more errors are found: undefined reference to dlopen, dlerror..... Add '"-ldl"' just below the '"-lpthread"' added earlier.
DONE :)

I didn't find a complete answer for Windows as a beginner, and at the beginning it is very painful to understand everything. So here's what worked for me.
Download the SQlite Amalgamation file.
Open Code::Blocks -> New Project -> Choose static library
Unzip the file you have downloaded and copy the folder/contents to your new project directory. Add all the files to the project and build the project.
You will find a ProjectName.a file in the bin/Debug or bin/Release directory. Copy that file to your actual SQlite project directory.
Go to Code::Blocks Project->Build options. Select 'Linker Settings' tab and add the path to the .a file. Don't close it yet!!!
In 'Search Directories' tab, select the 'Compiler' tab, add the path to the Amalgamation header files, or copy the header files to your directory (you can add the header files to your project) and in the 'Linker' tab add the path to the .a file
Now Compile!!! Hopefully this will run
That is all, I wish it'll save some searching time for another noob

You will need to compile the sqlite code first, and then just #include "sqlite3.h" into your project where you need it.
UPD:
Try this:
Download this package from sqlite site and extract it somewhere, say, into a folder called "sqlite". Open terminal, and go into this folder. Inside of it, run
./configure
sudo make
sudo make install
and see what happens. It should build itself automatically. Consult the README file that is inside the archive too.

Related

C++ Windows Driver MSB3030 could not copy the file '' because it was not found

VS2017, SDK/WDK, C++ project
we have a c++ solution (driver) that is shared across developers via Team Foundation Services - visualstudio.com (now called azure devops?).
When I perform a get latest source code, and want to rebuild the solution I get two MSB3030 errors:
"Could not copy the file "C:\path of my colleague his file" because it was not found."
I found it strange that I saw on one of the two errors a path of my colleague his pc. He works on C:\ I'm working on E:\
Unloading the project, I saw he path being set here:
<ItemGroup>
<FilesToPackage Include="C:\path of my colleague\foo.xml" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<PackageRelativeDirectory>
</PackageRelativeDirectory>
</FilesToPackage>
We cannot get this solution to build because of the MSB3030. First we have to clean the specific projects individually, rebuild it, then build another project etc.. a few steps to perform manually in the correct order , trial and error, drinking coffee, throwing bananas to the pc and praying that a monkey outputs the code correctly.
Has anyone seen somehting similar regarding MSB3030 errors?
On my pc I see the path of my colleague, but he doesn't see my path (strange!).
C:\Program Files (x86)\Windows
Kits\10\build\WindowsDriver.common.targets(1699,5): error MSB3030:
Could not copy the file 'C:...' because it was not found.
I've set the Any CPU to x64 because it doesn't make any sense for c++.
C++ Windows Driver MSB3030 could not copy the file '' because it was not found
The reason for this issue is that the path of the ItemGroup is an absolute path in the project file:
<ItemGroup>
<FilesToPackage Include="C:\path of my colleague\foo.xml" ...>
...
</FilesToPackage>
</ItemGroup>
Regardless of whether your colleague has added this file to source control, when you pull the code from the TFS server to your local and put the code in a different local folder, the absolute path will bring you a lot of trouble, you need to manually check the code on the TFS server for this file and you need to modify the absolute path of this file in your project. But this problem will reappear after your colleague updates after you submit your code. Because an absolute path cannot be assigned to two different paths C:\ and E:\.
To resolve this issue, you need to change the absolute path to a relative path in the source code. Generally, we prefer to add this file to the Solution/Project folder, then use the MSBuild Macros $(SolutionDir)/$(ProjectDir) to specify it.
Check Common macros for build commands and properties for some more details.
Hope this helps.

Can't find library png++

I'm trying to use the png++ library. Already added it to the library search path in eclipse (windows user, if relevant), but I get the
fatal error: png++/png.hpp: No such file or directory
I really don't know what to do.
Thank you!
Okay. You need to check your settings one by one.
It (png++) is a C++ library, so you must have C++ compiler set in your
run/debug settings.
Add your library include folder to that compiler's settings
To actually link to the library, you need to add the .lib/.a files or DLLs to linker settings.
I'm not much of a user of Eclipse CDT but that's how it works. If you are trying to do image manipulation without prior C++ experience, I suggest you to go with python/Java, they are easy to use.
After days, tears and blood, my professor (PhD Daniel Brake) figured it out! Here is what we did to make it work. I hope you never need to use this library on a Windows machine (conf: Windows 10, MinGW, Eclipse):
Make sure that you have the MinGW installation manager, have all the packages on the basic setup installed, and in "all packages", look for "msys-zlib", class dll
Now open the cmd (Windows+x, A, to open in admin mode)
You have to open the "msys.bat", go to C:\MinGW\msys\1.0\msys.bat
It will open a unix-like terminal, then type:
mingw-get install libz-dev
cd /path/to/libpng/folder
./configure -prefix=/mingw
make
make install
Google png++, download it, and using the MinGW terminal go to the folder that contains it:
cd /path/to/png++/folder
tar -zxf png++-0.2.x.tar.gz -C
In the png++ page, go to http://savannah.nongnu.org/bugs/?46312 and donwnload the file to the png++ folder
Replace the error.hpp file
Using a text editor, open the error.hpp file you just downloaded
Add #include <sstream> to the includes
look for the part and comment it:
strerror_r(errnum, buf, ERRBUF_SIZE);
return std::string(buf);
Now, add this in the same block of above:
std::stringstream ss;
ss << errnum;
return ss.str();
Save and close
Now, open Eclipse, create the project for the png++
Go to Configuration > C/C++ Build > set Configuration to "Debug [Active]"
Then C/C++ Build > Settings > GCC C++ compiler, add to "Include paths (-l)", the path to the folder png++ and the path to the folder that contains the file png.h, in my case it's in "C:\MinGW\msys\1.0\mingw\include"
Go to MinGW C++ Linker > Libraries, add to "Libraries (-l)" just the word "png" and in the "Library seach path (-L)" the path to the folder of libpng.a, in my case, "C:\MinGW\msys\1.0\mingw\lib"
save
to use it, in the header, add #include <png.hpp> (not #include <png++/png.hpp>)
it will have a warning, you can ignore it
it doesn't works!
in your MinGW terminal, go to the folder that have the "eclipse.exe" and open the Eclipse that way (don't ask me, my professor said something about path, I have no idea why)
Maybe you can simply use another compiler, but I couldn't, or use Linux.

New to Xcode can't open files in c++?

I've been using windows in a class I've been taking but I am trying to run a basic code to figure out how to open/close/input/output from files on Xcode and the code I usually use on visual studios isn't working any idea why? thanks!
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string input;
fin.open("inputFile.txt");
if(fin.fail())
cout << "File failed to open." << endl;
fin >> input;
fout.open("outputFile.txt");
fout << input;
}
Put your .txt files in the same directory where your main.cpp file is (or anywhere you like).
In Xcode go to Product > Scheme > Edit Scheme > Run (on the left) > Options (middle top)
Down under Options for "Working Directory" check “Use custom working directory” and set it to the directory where you .txt files are located.
To work with the files, you will have to specify just file names, e.g. in_file.open("inputFile.txt"); no path is necessary.
Here's a completely different approach: Have Xcode copy the input file for you.
Select your project in Xcode
Select Build Phases
Click the '+' button to create a new Build Phase
Select New Copy Files Build Phase
Select Products Directory
Click the '+' button to add your file
Click Add Other
Select your input file and click Open
Check the Copy items… checkbox and click Finish
Now every time you build your project, the input file will be copied to the same folder as the executable no matter where it is built. Of course, to see the output file, you'll still need to find the executable in Finder.
The answers don't really explain the problem so I thought I'd do that.
When you pass a relative path like "inputFile.txt" to file APIs, it's treated as relative to the working directory when the program is executed. This is the same as the 'working directory' when you use cmd.exe or Terminal.app or command lines in general. The Unix command pwd ("print working directory") displays the current working directory. On Windows running the command cd with no arguments performs the same function. (On Unix running cd with no arguments will change the working directory to the user's home directory.)
When you run a program from the command line, the command line shell sets the program's working directory. When you run a program from within an IDE, the IDE sets the working directory. Since, unlike on a command line, there's no obvious answer for what the IDE should set as the working directory, Visual Studio and Xcode set the working directory to different locations by default: Visual Studio sets the working directory to $(ProjectDir), the directory containing the Visual Studio project file; Xcode sets the working directory to the build products directory, i.e. the location the executable was written to.
Some possible solutions to your problem are:
Do not use a relative path, and therefore don't depend on the working directory. This isn't much help in making the program more portable, because the absolute paths will also differ between platforms, and so you will still have to 'configure' the program for each platform. In fact using an absolute path is worse, because it means your source code must differ, whereas it would be better to keep that difference confined to each platform's build configuration.
Configure the IDE to use your desired working directory. Visual Studio can be configured by right clicking the project, selecting Configuration Properties > Debugging > Working Directory, and setting the working directory to the desired path (potentially using Visual Studio build variables).
nepete's answer describes how to configure the working directly set by Xcode.
Configure the IDE's build process to copy your data files to an appropriate location. In Visual Studio you would do this in a C++ project by configuring the project's Properties > Configuration Properties > Build Events.
SSteve's answer covers how to configure additional build steps in Xcode.
I'm guessing you have inputFile.txt in the folder that contains your source code. That's not going to work. You need to put it in the folder that contains the generated executable. To find that folder, right-click on your app under Products and select Show In Finder.
This image shows what it looks like for a command line program. It also shows the Finder window that was opened. As you can see, it is a different folder than the one containing the source code.
As suggested by nepete, edit the scheme, but use $PROJECT_DIR as the custom working directory. Helps with moving the project around, or working in two different environments (e.g., home and office).
BTW. $PROJECT_DIR is one of the Xcode Environment Variables, and also helps with passing file names as command line arguments to programs (settable under "Arguments" in the scheme).
I've struggled with the same problem today. I wanted to add C code to my Swift project and my file pointer was always NULL.
Unfortunately, in XCode 9 for iOS app, I couldn't change the working directory. Changing Build phases didn't help me either. After 4+ hours of trial and error, that's what I've come up with finally and it works:
when copying files to XCode, I've chosen "Create groups", but I needed to choose "Create folder references":
I created a new objective-c file (.m) and copied all my C code there.
I left untouched .h files (XCode generated bridging header and my own .h file with public functions declaration). Now my project structure looked like this:
In my dict.m file in place of previous plain c fopen part:
FILE *dic = fopen("dictionary.txt", "r");
I added obj-C code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dictionary" ofType:#"txt"];
FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
And it works now without any problem! It's just amazing!
ps I decided to write this answer in case it will help someone like me and will save them some time. If you know how to change working directory in XCode 9 for iOS, please, leave me a comment - now I am really curious why I can't find it.

Boost in Netbeans 7.1.1

Trying to run the following:
#include<iostream>
#include<boost/filesystem/operations.hpp>
namespace bfs=boost::filesystem;
int main()
{
bfs::path p("second.cpp");
if(bfs::exists(p))
std::cout<<p.leaf()<<std::endl;
}
I got some errors in cygwin so I decided to try out netbeans, and used the following as a guide. I added all links and the following for filesystem Project -> properties -> Linker ->Libraries -> Add option -> Other -> -lfile_system as noted here. I have run a separate test using #include<boost/any.hpp> so I am not currently doubting that my boost is not installed correclty.
It seems weird to me that it is "file_system", so I also tried "filesystem" but to no avail.
When i hold Ctrl and click on #include<boost/filesystem/operations.hpp> my netbeans brings up my operations.hpp file so it seems okay (linked properly internally that it can "see" what I want it to see).
The solution to installing boost came in the following form:
1 - If you have any path variables that are being used for Visual Studio you should temporarily change the variable during installation. This is a good guide. Once that is done, this is one step completed.
2 - Download and install MinGW. This is a very easy process and you can find the installer files here.
Once you have done these things (if you are in the same situation as me), you will now be able to properly install boost.
Horay!
Using Boost with cygwin step by step
Create a new Project
It is better to take the names given here in this tutorial exactly. Later ask: It does not work, can then be easier to find.
I do not think I need to mention all T:\ must of course be replaced with your drive.
Project Name : Boost-cyg-Test
Now your Project should look like
Open main.cpp
Overwrite the generated code with the following. We want to that, first of all everything works without error.
Therefore, please do not use your own special code.
It is difficult to find a fault. Then told after several ask, to get:
I have used my own code
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("second.cpp");
if (exists(p)) { std::cout<<p.leaf()<<std::endl; }
}
In this section we assume that "boost" is already compiled.
goto Tools -> Options
Your C++ Code Assistance options should look something like this.
If this is not so, we should let Netbeans create that for us.
Add New Tool Collection
After we have completed this dialog with OK, we should find the settings shown above. ( C++ Code Assistance options).
Copy all libs into the right place
Let's create a new folder 'boost'.
With a search tool, search in your compiled Boost folder for *.a
My Boost is compiled with the shared option so we find :
For our short App. we need only 2 files.
libboost_filesystem-gcc45-mt-d-1_53.dll.a
libboost_system-gcc45-mt-d-1_53.dll.a
But if we're at it to copy two files, we can copy all files.
So mark all found .a files and copy them into the directory just created
T:\cygwin\lib\boost .
Now we do the same with our .dll files.
Mark all .dll files and copy it in your ?:\cygwin\bin directory.
If you only have compiled static librarys, you can skip this point.
Now it's time to modify our project settings.
As you can see i put my source Boost folder into cygwin
and
As we have already noted above, we need two .a files.
with Add Library navigate to T:\cygwin\lib\boost and select
libboost_filesystem-gcc45-mt-d-1_53.dll.a
libboost_system-gcc45-mt-d-1_53.dll.a
Now you'll notice that this name was shortened by netbeans to:
boost_filesystem-gcc45-mt-d-1_53.dll
boost_system-gcc45-mt-d-1_53.dll
This is somewhat confusing. It looks as if a .dll is standing here. But it is really a .a file.
Set a breakpoint in main.cpp. Now we start debug.
I have marked the important part, the two libs, with an arrow.
All libs are found and after make has finished, stops at the breakpoint.
The output:
Build Boost for Cygwin
For all who want to create boost with shared library itself.
Download boost_1_53_0.zip
Create a folder in your ?:\cygwin directory.
boost_1_53_0
Extract the zip file into that directory.
It should look like:
open a cmd window, cd to boost_1_53_0 directory.
To have a clean build we need a PATH that have only the cygwin home and bin.
In the cmd type.
SET PATH=T:\cygwin;T:\cygwin\bin
and test the path.
PATH
Type
bootstrap.bat
Type
.\b2 --build-dir=T:\boost-cyg toolset=gcc variant=debug link=shared runtime-link=shared
After some time the build is finished.
Now you have the same environment that we have used in the tutorial.
If you get a Error : gcc not found
copy (not rename) in ?:\cygwin\bin folder, for example : (names may differ).
i686-pc-cygwin-gcc-4.5.3.exe to gcc.exe
and
i686-pc-cygwin-g++-4.exe to g++.exe
Hope it helps you.
Could you paste the error you get when compiling ?
I am not used to compile programs in a Windows environment, but I think as Jesse Good suggested in a comment that you have a linker error.
You may solve it by using -lboost_filesystem instead of lfile_system.
To find out how your libs are called, you get the name of your lib (on my unix environment I have libboost_filesystem.so), strip the "lib" prefix and the ".so" or ".a" suffix (must be different in a Windows environment).
if your boost installation is correct and you are sure about it then for Unable to resolve identifier try Code Assistance->Reparse Project from context menu of the project. It tries to recover broken code model by reparsing project from scratch. if that didn't workout try closing IDE and removing code model cache.
p.s. do you have compilation errors?

"Error C1083: Cannot open source file" Shouldn't Be Looking For The File At All

I was trying to #include a cpp file with some functions so I can use that cpp file later with other projects. It gave me an 'already defined in .obj' error and since then that .cpp file was like binded with my project. (I understood that's not the way, the answer here helped me with the already defined)
If I exclude the .cpp file from the project, remove it from the directory and remove the #include line it still looks for it:
c1xx : fatal error C1083: Cannot open source file: 'std.cpp': No such file or directory
Diagnostic:
Outputs for D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\CBMAIN.CPP|D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\STD.CPP: (TaskId:15)
It shouldn't be looking for the std.cpp at all, I removed it! So is there a way I can reset the project and recompile so that the program doesn't look for it? I already tried Rebuild and Clear -> Build Project
When I ran across a similar problem with VS Express, I wound up having to open up the the .vcxproj file (which is just XML), and remove the offending
< ClInclude Include="FILEPATHANDNAME" > tags.
Many of the solutions here will not work
Fullproof method:
Open the vxproj file that is giving you trouble in a text editor.
remove all references to the file it cannot find.
OK, I have no idea how I did it but I'm still going to try to write what I did.
Save all and Close solution
Open the .vcxproj file (not .sln)
Build -> Clean [Project Name]
Save all and Close
Open the .sln file again.
Build -> Project Only -> Clean Only [Project Name]
Build -> Project Only -> Build Only [Project Name]
That's exactly what I did and worked for me. I think the main thing to do is clean, save, close, open, build, but I'm not sure.
In Solution Explorer you can select/deselect option "Show All Files".
Try both options and make sure excluded file is not included in project for both of them.
That's what I had:
I used "Show All Files" option (so you can see all the files in project directories). I excluded one of my .cpp files from project. However, it behaved as this file is in project.
That's how I managed to fix it:
I switched "Show All Files" off and saw this file still belongs to project! So I excluded this file once again.
As I see, that's a known issue.
This worked for me, hope it will be useful for someone else.
Try to verbose builder output to see exact steps of what's going on. I suppose, you use Visual Studio, right?
Go to menu "Tools -> Options"
In options dialog, select "Projects and Solutions -> Build and Run"
Change current mode of "MSBuild project build output verbosity" from "Minimal" to something like "Diagnostics" or "Detailed".
Rebuild your project and investigate Output windows
Builder dump should shed more light on your current settings (I suspect you have more references to that file than you expect)
This happened to me because I renamed folder from inside the IDE. None of the above solutions worked. The only way to fix this is by opening vcproj in notepad and you should see the offending files in the <ItemGroup>. Just delete those lines.
Or sometimes, like in my case, the issue is simply in the naming of the folders in the location. I had a very long path with folders that I like to name with special characters so they show up at the top and it's easy to access them.
As soon as I put my solution in a folder just in D: drive, the issue was gone.
When I renamed a file, I found I had to go to SolutionExplorer, Source File, select the file, first exclude from Project, then re-add it to project, and rebuild the solution it lives in. It was still showing up as the old file name under Source Files for me.
I had the same problem, but I had another .sln worked fine. After tooling around with the Project->Properties-> to make them look identical, nothing worked. I opened both .vcxproj files and copied the contents of the working version into my non-working version. (I noticed that the two files had different lengths. The non-working version was longer by about 20 lines.) I just changed the RootNameSpace to the non-working version's name. I saved the non-working file and presto! It worked.
I removed those sources from Project and re-added them. Somehow, references were messed up after a hurry project refactoring.
For people having problem related to "error C1083: Cannot open source file":
Error is caused by settings in *.vcxproj file. Probably you deleted/moved source file by file explorer, not by Visual Studio's "Solution Explorer". Thus, your *.vcxproj file is corrupted. Fix is to manually correct settings in *.vcxproj file.
How Visual Studio settings files work
Visual Studio saves solution's info into file. This file is usually in project's solution directory, has extension .sln and base name is same as name of solution, f.ex.:
NameOfSolution.sln
Similarly, project's info is saved into one file (each project has its own file). Base name of this file is name of project, extension is .vcxproj, and usually is located in subdirectory named as your project, f.ex.:
NameOf1stProject/NameOf1stProject.vcxproj
NameOf2ndProject/NameOf2ndProject.vcxproj
Both *.sln and *.vcxproj files are textual files. You can open them by using Notepad.
How to fix problem
Find *.vcxproj file responsible for your project.
If you don't know where it is, open in Notepad the *.sln file of your solution. Search for name of your solution. You will find line like:
Project("{9AA9CEB8-8B4A-11D0-8D22-00B0C01AA943}") = "NameOf1stProject", "NameOf1stProject\NameOf1stProject.vcxproj", "{A8735D0A-25ED-4285-AB8F-AF578D8DB960}"
Value under "NameOf1stProject\NameOf1stProject.vcxproj" is location of *.vcxproj file of your project.
Open found *.vcxproj file by text editor (f.ex. Notepad).
Search for line on which is filename you are struggling with.
Example: if you are looking for "RemovedFile.cpp", then you should find line:
<ClCompile Include="RemovedFile.cpp" />
Delete that line.
If you have opened Visual Studio, it asks you if it should refresh solution - select yes. If it is not opened - just start using it.
In case of any problems, try to rebuild solution (top banner -> Build -> Rebuild Solution)
In my cases, it worked. 30 mins of trying to fix, <1 minute of fixing.
This helped in my case. To sum it up, my path to the project was too long, so I moved my project to something shorter i.e. D:\my_project and everything worked in a blink of an eye.
I had this same problem, but for me the issues was that I was using Bash on Windows (WSL) to clone the repository and then using VS to compile.
Once I deleted my clone and used Windows command line (cmd.exe) to clone the repo then the error 1083 went away.
This is caused by not removing/deleting the file properly. Go to Solution Explorer, select your solution, at the left corner, activate the icon: show all files.
(if you already removed the problem file, restore it from recycle bin)
Select the problem file, do remove and delete from within Solution Explorer and you should not have this problem. And remember to do it the proper way from now on.
This is on MS 2010
If you have that file in your project directory but you still got the error, on your IDE go to Solution explorer--> Remove that file-->then open the project directory on your file explorer-->Select that file and drop it on a specific location in IDE solution explorer. I fixed it this way. I use the Windows platform.
I got this error when I got a code from my peer and I tried directly running it on my system. Ideally to avoid such errors, I should have just copied the source and header files and should have created the VS solution of my own.
To resolve the errors I removed the files from the Solution Explorer and added them again. Following image shows the Solution Explorer window.
The remove option comes after right clicking on the file names.