How can I use functions from different projects in Eclipse? - c

I have 2 C projects in eclipse, each one do a specific work.(In one project I have dataCatcherXML.c and in the other project I have main.c)
The 1st take the value of some variables from a specific xml code and the other one has variables that must have the value taken in XMLdataCatcher.
Each one works in their specific project but If I merge both of the files(dataCatcherXML.c and main.c) in one project, it doesn't work.(And I don't know why)
So I decided to work with this files in different projects.
My questions is How can I use together this functions from different projects? Is it possible?
dataCatcherXML.C (As you can see here I am taking the value of bit error, bit error is a tag in a XML file)
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <xmlmemory.h>
#include <parser.h>
#include <xmlstring.h>
#include "crc.h"
void XMLdataCatcher(int argc, char **argv) {
xmlDocPtr doc;
xmlNodePtr root;
xmlNodePtr node;
xmlNodePtr children;
xmlNodePtr children2;
doc = xmlParseFile("/home/practicante/XML/prueba1.xml");
if (!doc) {
printf("Error al cargar documento XML\n");
}
root = xmlDocGetRootElement(doc);
node = root->xmlChildrenNode;
while (node != NULL ) {
children = node->xmlChildrenNode;
while (children != NULL ) {
**//In this part I am taking the value of bit_error from the XML file**
if (!(xmlStrcmp(node->name, "bit_error"))) {
printf("%s: %s\n", node->name, xmlNodeGetContent(node));
printf("%s\n", bit_error);
strcpy(bit_error, xmlNodeGetContent(node));
printf("%s\n", bit_error);
}
children2 = children->xmlChildrenNode;
while (children2 != NULL ) {
printf("%s: %s\n", children->name, xmlNodeGetContent(children));
children2 = children2->next;
}
children = children->next;
}
node = node->next;
}
printf("bit_error2 = %d", 1);
}
main.c:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <xmlmemory.h>
#include "crc.h"
#include <parser.h>
#include <xmlstring.h>
#define BIT_SINCRONIA 0X47
#define PID_PAT 0X00
#define table_pat 0x00
FILE *fp2;
int main() {
unsigned short bit_error = 0; // **This part should be: unsigned short bit error = (the value taken in dataCatcherXML)**
bit_error = bit_error << 15;
unsigned short init_payload = 1;
init_payload = init_payload << 14;
unsigned short transport_priority = 0;
transport_priority = transport_priority << 13;
unsigned short PID = PID_PAT;
PID = transport_priority ^ PID;
PID = bit_error ^ PID;
PID = PID ^ init_payload;
unsigned short PID1 = PID >> 8;
unsigned short PID2 = PID;
......... the rest of the code is irrelevant
}
Thanks in advance.

It's hard to give a sane answer to such question, but I'll try with some variants.
Simple one: just copy (or link) the file from one project to another. You will need to remember about syncing it between two projects if any changes happens.
Do It In Eclipse Way: well, this one is kindly ironic, but if you really want to do it as Eclipse wants you to do it you can try this. Create a separate project. This project would contain only this dataCatcherXML.c. This project should compile into a static (because it's easier than shared) library, let's say: datacarcherxml.a. In other projects requiring this library you need to set dependencies on the datacatcherxml.a and add a library from other project. If you do that correctly datacatcherxml will be rebuild if required. Well, it's a little baroquesque, but what would you expect from IDE designed originally for Java? (Ok, it was a litle trolling, sorry about that).
To be honest, it would work that way for Java projects, I'm not sure about the CDT plugin. I'm using Eclipse only for Java. I'm rather old-schooler and I prefer well-configured vim for C/C++ development.

Related

ECDSA ciphering with OpenSSL results in memory problem

I'm trying to encrypt a message using the ECDSA algorithm with OpenSSL (1.1.1), but I must be doing something wrong with my pointers, because everytime I run the code, it gives me a different result.
Here's what I do:
create a key using custom curve parameters (with BN_hex2bn);
sign a simple message using ECDSA_do_sign;
split the message into the R and S points (ECDSA_SIG_get0_r and ECDSA_SIG_get0_s);
display the resulting R point.
And the display value is always different, while I expect it to be the same (because same message and same key). I think some memory is deallocated somewhere, giving me a pointer to invalid data, but I'm not sure about it; I have checked:
the keys are ok, and they are valid according to EC_KEY_check_key;
the two variables s and r are already wrong, hence it doesn't come from BN_bn2bin.
Here is my code if you want to give a try:
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/ecdsa.h>
#include <openssl/buffer.h>
int main(void) {
ECDSA_SIG *sig;
EC_KEY *eckey;
BIGNUM *priv_key = BN_new();
BIGNUM *x_key = BN_new();
BIGNUM *y_key = BN_new();
const char digest[] = "Hello, world!";
eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
// Set predefined keys
BN_hex2bn(&priv_key, "8e9b109e719098bf980487df1f5d77e9cb29606ebed2263b5f57c213df84f4b2");
BN_hex2bn(&x_key, "7fcdce2770f6c45d4183cbee6fdb4b7b580733357be9ef13bacf6e3c7bd15445");
BN_hex2bn(&y_key, "c7f144cd1bbd9b7e872cdfedb9eeb9f4b3695d6ea90b24ad8a4623288588e5ad");
EC_KEY_set_private_key(eckey, priv_key);
EC_KEY_set_public_key_affine_coordinates(eckey, x_key, y_key);
sig = ECDSA_do_sign(digest, 32, eckey);
// Get the resulting point
const BIGNUM *r = ECDSA_SIG_get0_r(sig);
const BIGNUM *s = ECDSA_SIG_get0_s(sig);
unsigned char rc[256];
unsigned char sc[256];
BN_bn2bin(r, rc);
BN_bn2bin(s, sc);
// Print the result: some memory problem...
for(int i = 0; rc[i] != 0; i++) {
printf("%d ", rc[i]);
}
return 0;
}
Do no forget to link the libraries when you compile it: gcc -g -o main main.c -lssl -lcrypto.

Creating array of strings works in source code doesn't work in executable

I've got some code which generates an array of strings of different file names and then
passes them into a function to write some data to them. It adds a incrementing number to the starting filename which is supplied from an input argument.
The problem is that it works fine running from source in Visual Studio 2012 but when I compile it and run it as an .exe the program crashes.
The .exe doesn't appear to be passing the array of strings properly which is causing an error when it attempts to use the string
for opening a file etc.
Here is the isolated bit of code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <stdint.h>
#include <Windows.h>
void processing_function(int num_output, char **outnames)
{
/* in Visual Studio this works fine and prints all
the names correctly. Running from .exe will crash */
for(int idx = 0; idx <num_output;idx++)
{
printf("outnames[%d] is %s\n",idx,outnames[idx]);
}
}
int main(int argc, char *argv[])
{
/*nframes comes from another function, outname comes from input arguement */
int num_output = ceil(((double)*nframes / 1100));
int outname_len = strlen(outname)+1;
char *out_right;
out_right = (char*) malloc(sizeof(char)*outname_len);
/*Split string to append numbers before file extension */
strcpy(out_right,outname);
strrev(out_right);
strtok(out_right,".");
strcat(out_right,".");
strrev(out_right);
int out_right_len = strlen(out_right);
strtok(outname,".");
strcat(outname,"-");
int out_origlen = strlen(outname);
int num_len = 1;
char **outnames;
char *num;
char *outname_tmp;
outnames = (char**) malloc(sizeof(char)*(num_output));
int out_len;
double dbl_idx;
int *numfs = (int*)malloc(sizeof(int)*num_output);
for(int idx = 1;idx <num_output+1;idx++)
{
/*convert output number to string and stitch complete name back together and place into array */
num_len = ceil(log10((double)idx+0.1));
num = (char*) malloc(sizeof(char)*(num_len+1));
outname_tmp = (char*) malloc(sizeof(char)*(out_origlen+num_len+out_right_len+1));
strcpy(outname_tmp,outname);
sprintf(num,"%d",idx);
strcat(outname_tmp,num);
free(num);
strcat(outname_tmp,out_right);
outnames[idx-1] = (char*) malloc(sizeof(char)*(out_origlen+num_len+out_right_len+1));
strcpy(outnames[idx-1],outname_tmp);
free(outname_tmp);
printf("%s\n",outnames[idx-1]);
}
free(out_right);
processing_function(num_ouput, outnames)
return(0);
}
EDIT: Changed num_input to num_output as they do have the same value.
Running from .exe will sometimes start printing some of the names and then crash, opening the
debugger gives an error within output.c, with an access reading violation. I tried putting this code at
the top of the processing_function but that gave further problems downstream (heap corruption), which makes me think that the
code is messing up the memory but I can't see whats wrong with it, nor why it would work in VS but not as a .exe.
I could try and dodge the issue by generating the next output name on the fly every time it requires one but I'd really rather know why this isn't working.
Any help would be greatly appreciated.
I am going to take a shot and say, you passed num_input to processing_function() with outnames, outnames was allocated with num_output for size, but num_input and num_output have different values at runtime. So that lets processing_function() access out of bounds.

File Finder in C

First of all Sorry for my bad English. I am not native English.
I am going to write a program that list all available logical disk drives. Then ask the user to select a drive. then takes a file extension and searches that file type in given drive (including directories and sub-directories). Program should be able to run on windows xp and onward. It should be single stand alone application. I am not expert in C. I have some hands on C#. i have following questions in this regard.
1. Is there any IDE/Tool in which i can write C# like code that directly compiles to single stand alone application for windows?
2. Can you recommend some libs that i can use state forward for this purpose like using in C#? (I have seen dirent and studying it.)
I coppied some code that i am testing as a startup.
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <tchar.h>
#include<conio.h>
#include<dirent.h>
//------------------- Get list of all fixed drives in char array. only drive letter is get. not path.
// add ":\" to build path.
char AllDrives[26];
DWORD GetAllDrives()
{
int AvlDrives=0;
DWORD WorkState=-1;
//TCHAR DrivePath[] = _T("A:\\"); //Orignal Type
//start getting for drive a:\ to onward.
char DrivePath[] = {"A:\\"};
//http://www.tenouk.com/cpluscodesnippet/getdrivetype.html
ULONG uDriveMask = _getdrives();
if (uDriveMask == 0)
{
WorkState=GetLastError();
printf("\r\nFailed to Get drives. Error Details : %lu", WorkState);
return WorkState;
}
else
{
WorkState=0xFF;
printf("The following logical drives are being used:\n");
while (uDriveMask) {
if (uDriveMask & 1)
{
UINT drvType=0;
drvType = GetDriveType(DrivePath);
if(drvType==3)
{
AllDrives[AvlDrives]= DrivePath[0];
AvlDrives++;
printf("\r\n%s",DrivePath);
}
}
++DrivePath[0]; //Scan to all scanable number of drives.
uDriveMask >>= 1;
}
}
return WorkState;
}
int main(int argc, char* argv[]) {
char DrivePath[]={"C:\\"};
char CurrentDrive[]={"C:\\"};
DWORD Drives=-1;
int d=0;
for( d=0; d<26; d++)
AllDrives[d]=' ';
Drives=GetAllDrives();
if(Drives >0)
{
int Length= sizeof(AllDrives);
for(int x=0; x<26; x++)
{
if(AllDrives[x]!=' ')
{
printf("\r\nFixed Drive : %c",AllDrives[x]);
}
}
}
getch();
}
You can use visual studio compiler to compile C and C++ in Windows, and it is available with its own IDE. When you install visual studio, it will install required libraries also to compile the C/C++ program. There are other IDEs and compilers available compatible with Windows like DevC++,CodeBlocks.

C get battery life under Windows 7

I'm trying to code a program that gets the % of a laptop battery and then displays a CMD showing a message (for example: 10% -> "Low battery!").
I've tried to google it, and it seems they all tried with C++ or C#.
Can anybody help me with C, please?
Edit: thanks zakinster for your reply. Shouldn't it look something like this? This code ain't working.
#include <Windows.h>
#include <Winbase.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
SYSTEM_POWER_STATUS status;
GetSystemPowerStatus(&status);
unsigned char battery = status.BatteryLifePercent;
printf("%s", battery);
}
GetSystemPowerStatus from the Win32 API should provide the information you need :
SYSTEM_POWER_STATUS status;
if(GetSystemPowerStatus(&status)) {
unsigned char battery = status.BatteryLifePercent;
/* battery := 0..100 or 255 if unknown */
if(battery == 255) {
printf("Battery level unknown !");
}
else {
printf("Battery level : %u%%.", battery);
}
}
else {
printf("Cannot get the power status, error %lu", GetLastError());
}
See the documentation of the SYSTEM_POWER_STATUS structure for a complete list of contained information.

Why all these errors when building this C project?

I'm coding some similar programs in C as part of an XCode project. As this new program needs to exhibit some slightly different functionality to what the 1st working iteration was, I thought targets were the best thing to use.
So I tried to create a new target, and did it the way I thought was the right way from googling how to (in XCode). But on compilation, I get way too many errors.
Here is a screen of the errors I get:
I see that it's having a problem with loads of different characters, so I'm sure it's probably a simple problem like some missing files. But I didn't know what to Google so I hope it's okay that I'm asking.
On a related note, does anyone know why my first version of the program, called main.c, didn't need to include a header file like the one above did?
Thanks!
EDIT:
Here's the code from the new target, which is practically identical to the so far unchanged first version of the program:
/*
* ScalarProduct.c
* Concurrency_Practical1
*
* Created by Chucky on 11/03/2012.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include "ScalarProduct.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//the final answer
int finalScalarProd;
//random variable
int rand_seed=10;
int rand()
{
int n;
n = random()%11;
//printf("%d\n", n);
return(n);
}
void* getScalarProduct(void *arg)
{
//index for loop
int i;
//scalarProduct of 10 integers
int * scalarProd = (int *) arg;
//my two arrays
int list1[10];
int list2[10];
for (i=0; i<10; i++) {
list1[i] = rand();
list2[i] = rand();
*scalarProd += list1[i]*list2[i];
printf("%d:\t\t %d\t\t %d\t\t %d\t\t\n", i, list1[i], list2[i], list1[i]*list2[i]);
}
return((void*)scalarProd);
}
int main (int argc, const char * argv[]) {
// insert code here...
pthread_t t1, t2;
int sp1= 0, sp2 = 0;
printf("Index\t List1\t List2\t Product\n\n");
pthread_create( &t1, NULL, getScalarProduct, &sp1);
pthread_create( &t2, NULL, getScalarProduct, &sp2);
pthread_join( t1, NULL);
pthread_join( t2, NULL);
printf("\nScalar Products: %d %d\n", sp1, sp2);
finalScalarProd = sp1 + sp2;
printf("Result: %d\n", finalScalarProd);
return 0;
}
From the errors, it almost looks as if you are mixing Objective-C headers and compiling with the C compiler. It's still hard to tell though.
Your project is including/importing the AppKit-Header, which is ObjectiveC and not pure C.
As your quoted source does not mention it, I would bet that it is imported within the precompiled header. Check your project's precompiled header for such entry/ies. It will be named just like your project, with the extension .pch. You may want to remove any ObjectiveC imports.
Also check if you used any ObjectiveC frameworks in your project. When in doubt, remove all listed frameworks from your project.

Resources