C++ program called "Palindrome integer" two func. Function 1// Return reversal integer. Function 2// Returns true if palindrome - function

Please Help
I am writing a program in C++ using visual basic 2010 the program is called "Palindrome integer" I need to write two functions one that//Return the reversal of an integer. For example reverse(456) returns 654
//with header:-->
int reverse(int number)
I need to write another function that//Returns true if number is a palindrome
//with header:-->
bool isPalindrome(int number)
I need to use the reverse function to implement the function isPalindrome. A number is a palindrome if the numbers reversal is the same as itself. My program should report whether the number is a palindrome. Everything is in one file.
I think this program worked when I first wrote the code not as two functions but just directly into int main(). But I must put the code into the specified two functions and once I had done that and made the adjustments I got the following error messages and the black cout display box didn't appear. Here's a snippet of the error report followed by the full error report
: error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
:fatal error LNK1169: one or more multiply defined symbols found
I'm getting the following Error Report
1>------ Build started: Project: Palindrome integer, Configuration: Debug Win32 ------
1>Build started 12/7/2013 4:54:25 PM.
1>InitializeBuildStatus:
1> Touching "Debug\Palindrome integer.unsuccessfulbuild".
1>ClCompile:
1> All outputs are up-to-date.
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>implementation.obj : error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
1>c:\documents and settings\dell\my documents\visual studio 2010\Projects\Palindrome integer\Debug\Palindrome integer.exe : fatal error LNK1169: one or more multiply defined symbols found
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.25
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
//Bellow is my Code
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//Retun reversal of an integer
int reverse(int number); //function prototype
//Return true if number is a palindrome
bool isPalindrome(int number); //function prototype
//Driver
int main()
{
int usersNumber = 456; //0; //a few lines commented tempararily for easier number testing
// cout<<"Enter a number and I'll tell you if it's a Palindrome: ";
// cin>> usersNumber;
bool palindromeToF = (isPalindrome(usersNumber));
if (palindromeToF == true)
{
cout <<"YES the number is a Palindrome";
}
else
{
cout <<"NO the number is not a Palindrome";
}
return 0;
}
//function Implementation
//Retun reversal of an integer
int reverse(int number)
{
//do while loop to count number of digits in Number
int digitsCount = 0;
double exponent1 = 1.0;
int quotient;
do
{
int tenToPower = pow( 10.0, exponent1);
// cout <<"tenToPower "<< tenToPower <<"\t ";
quotient = (number / tenToPower);
// cout <<"exponent1 "<< exponent1<<"\t ";
exponent1++;
//cout <<"quotient "<< quotient<< "\t "<<endl;
digitsCount++;
}while (!quotient == 0);
//populating array "arrDigits" with integer's digits
int *arrDigits = NULL;
arrDigits = new int[digitsCount];
double exponent2 = 0.0;
for(int i = 0; i < digitsCount; i++)
{
int powerOfTen = pow( 10.0, exponent2);
//cout <<endl<<"adding "<<((number / powerOfTen) % 10) <<" to sum";
//cout <<powerOfTen;
arrDigits[i]= ((number / powerOfTen) % 10);
exponent2++;
}
//reverse number & populate array "arrDigRevers" with reversed order number
int *arrDigRevers = NULL;
arrDigRevers = new int[digitsCount];
int j = 0;
int reversedNum = 0;
double exponent3 = 0.0;
for(int i = digitsCount-1; i >= 0; i--)
{
int powerOfTenB = pow( 10.0, exponent3);
reversedNum += (powerOfTenB * arrDigits[i]); //return of reverse func.
exponent3++;
/* //reversed integer put into array
if(j < digitsCount)
{
arrDigRevers[j] = arrDigits[i];
//cout <<"\t"<< "arrDigRevers"<<"["<< j<<"]="<< arrDigRevers[j]<<" "<< "arrDigits"<<"["<< j<<"]="<< " "<<arrDigits[j]<<" ";
j++;
}
*/
}
delete[] arrDigits;
delete[] arrDigRevers;
arrDigits = NULL;
arrDigRevers = NULL;
//cout <<endl<<"reversed number is "<< reversedNum;
return reversedNum;
}
//function Implementation
//Return true if number is a palindrome
bool isPalindrome(int number)
{
if(number == reverse(number))
{
return true;
}
else
{
return false;
}
}

The answer lies here:
1>implementation.obj : error LNK2005: "int __cdecl reverse(int)" (?reverse##YAHH#Z) already defined in Driver.obj
It appears that have defined int reverse(int number) in both implementation.cpp and Driver.cpp. You need to rename or remove one of these definitions from your project.

Related

How is it possible to compile code from code

I want to experiment with the programs that write programs in C code, and i want to use construction like following:
int main() {
char* srcCode="int f(int x) { return x+42; }";
int (*compiledFun)(int) = compile(srcCode);
printf("result=%d", (*compiledFun)(123));
return 0;
}
Desired output should be printed "result=165".
My question is about compile() function. I may try to put srcCode in a file, then invoke external compiler, like gcc, then try to read produced binary, probably fix some addresses, and so to fill the compiledFun memory. But I feel like that would be a very inefficient stub. Is there any way to compile a program from within a program, directly from memory to memory? Maybe some library or a subset that can be ripped off gcc sources, responsible for producting binary code from source text?
That may be important addition, all source code that should be compiled is a function that takes arguments and returns. It will not call any external libraries and function like printf, but only do some calculations and return.
Use libtcc an in-memory C compiler from TinyC.
A complete example from here https://github.com/TinyCC/tinycc/blob/mob/tests/libtcc_test.c
/*
* Simple Test program for libtcc
*
* libtcc can be useful to use tcc as a "backend" for a code generator.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libtcc.h"
/* this function is called by the generated code */
int add(int a, int b)
{
return a + b;
}
/* this strinc is referenced by the generated code */
const char hello[] = "Hello World!";
char my_program[] =
"#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
"extern int add(int a, int b);\n"
"#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
" __attribute__((dllimport))\n"
"#endif\n"
"extern const char hello[];\n"
"int fib(int n)\n"
"{\n"
" if (n <= 2)\n"
" return 1;\n"
" else\n"
" return fib(n-1) + fib(n-2);\n"
"}\n"
"\n"
"int foo(int n)\n"
"{\n"
" printf(\"%s\\n\", hello);\n"
" printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
" printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
" return 0;\n"
"}\n";
int main(int argc, char **argv)
{
TCCState *s;
int i;
int (*func)(int);
s = tcc_new();
if (!s) {
fprintf(stderr, "Could not create tcc state\n");
exit(1);
}
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
for (i = 1; i < argc; ++i) {
char *a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a+2);
else if (a[1] == 'I')
tcc_add_include_path(s, a+2);
else if (a[1] == 'L')
tcc_add_library_path(s, a+2);
}
}
/* MUST BE CALLED before any compilation */
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
if (tcc_compile_string(s, my_program) == -1)
return 1;
/* as a test, we add symbols that the compiled program can use.
You may also open a dll with tcc_add_dll() and use symbols from that */
tcc_add_symbol(s, "add", add);
tcc_add_symbol(s, "hello", hello);
/* relocate the code */
if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
return 1;
/* get entry symbol */
func = tcc_get_symbol(s, "foo");
if (!func)
return 1;
/* run the code */
func(32);
/* delete the state */
tcc_delete(s);
return 0;
}

Cuda get gpu load percent

I want to calculate the GPU load. How get gpu load percent in cuda?
enter image description here
http://eliang.blogspot.com.by/2011/05/getting-nvidia-gpu-usage-in-c.html?m=1
//
// Getting Nvidia GPU Usage
//
// Reference: Open Hardware Monitor (http://code.google.com/p/open-hardware-monitor)
//
#include <windows.h>
#include <iostream>
// magic numbers, do not change them
#define NVAPI_MAX_PHYSICAL_GPUS 64
#define NVAPI_MAX_USAGES_PER_GPU 34
// function pointer types
typedef int *(*NvAPI_QueryInterface_t)(unsigned int offset);
typedef int (*NvAPI_Initialize_t)();
typedef int (*NvAPI_EnumPhysicalGPUs_t)(int **handles, int *count);
typedef int (*NvAPI_GPU_GetUsages_t)(int *handle, unsigned int *usages);
int main()
{
HMODULE hmod = LoadLibraryA("nvapi.dll");
if (hmod == NULL)
{
std::cerr << "Couldn't find nvapi.dll" << std::endl;
return 1;
}
// nvapi.dll internal function pointers
NvAPI_QueryInterface_t NvAPI_QueryInterface = NULL;
NvAPI_Initialize_t NvAPI_Initialize = NULL;
NvAPI_EnumPhysicalGPUs_t NvAPI_EnumPhysicalGPUs = NULL;
NvAPI_GPU_GetUsages_t NvAPI_GPU_GetUsages = NULL;
// nvapi_QueryInterface is a function used to retrieve other internal functions in nvapi.dll
NvAPI_QueryInterface = (NvAPI_QueryInterface_t) GetProcAddress(hmod, "nvapi_QueryInterface");
// some useful internal functions that aren't exported by nvapi.dll
NvAPI_Initialize = (NvAPI_Initialize_t) (*NvAPI_QueryInterface)(0x0150E828);
NvAPI_EnumPhysicalGPUs = (NvAPI_EnumPhysicalGPUs_t) (*NvAPI_QueryInterface)(0xE5AC921F);
NvAPI_GPU_GetUsages = (NvAPI_GPU_GetUsages_t) (*NvAPI_QueryInterface)(0x189A1FDF);
if (NvAPI_Initialize == NULL || NvAPI_EnumPhysicalGPUs == NULL ||
NvAPI_EnumPhysicalGPUs == NULL || NvAPI_GPU_GetUsages == NULL)
{
std::cerr << "Couldn't get functions in nvapi.dll" << std::endl;
return 2;
}
// initialize NvAPI library, call it once before calling any other NvAPI functions
(*NvAPI_Initialize)();
int gpuCount = 0;
int *gpuHandles[NVAPI_MAX_PHYSICAL_GPUS] = { NULL };
unsigned int gpuUsages[NVAPI_MAX_USAGES_PER_GPU] = { 0 };
// gpuUsages[0] must be this value, otherwise NvAPI_GPU_GetUsages won't work
gpuUsages[0] = (NVAPI_MAX_USAGES_PER_GPU * 4) | 0x10000;
(*NvAPI_EnumPhysicalGPUs)(gpuHandles, &gpuCount);
// print GPU usage every second
for (int i = 0; i < 100; i++)
{
(*NvAPI_GPU_GetUsages)(gpuHandles[0], gpuUsages);
int usage = gpuUsages[3];
std::cout << "GPU Usage: " << usage << std::endl;
Sleep(1000);
}
return 0;
}

C++ - Exception handling

I'm learning exception handling in C++. Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
class point{
private:
float x, y;
public:
enum Error{
negative_coordinates,
};
point();
point(float, float);
~point();
float return_x();
float return_y();
};
point::point(){
}
point::point(float a, float b){
if(x < 0 && y < 0){
throw negative_coordinates;
}
else{
x = a;
y = b;
}
}
point::~point(){
}
float point::return_x(){
return x;
}
float point::return_y(){
return y;
}
int main()
{
try{
float x, y;
cout << "Enter coordinates of some point: " << endl;
cin >> x >> y;
if(x < 0 && y < 0){
throw (0);
}
}
catch(point::Error e){
const char * message [] = {"You entered negative coordinates"};
cout << "" << message[e] << endl;
}
}
If I put two negative values I got this:
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Process returned 3 (0x3) execution time : 5.420 s
Press any key to continue.
Any idea?
You throw an 'int' when you enter two negative values, but you catch a point. The types of your throw and catch need to be the same. If I change: catch(point::Error e) to catch(int e), the program runs fine.
As per: http://www.cplusplus.com/doc/tutorial/exceptions/

How to reverse a structure in text file with C?

I have an exercise and I don't know how to solve it well!
I want write a C program that give from user the information of a student and then save it to file A.txt. After that reverse the first name, last name and student number and save it to file B.txt.
For example:
john
lopez
123456
It changes to:
nhoj
zepol
654321
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
struct student {
char fname[SIZE];
char lname[SIZE];
char num[SIZE];
}st;
int main()
{
FILE *in, *out;
char ch;
int tmp=0,flag=0,i;
printf("INPUT First name: ");
scanf("%s", &st.fname);
printf("INPUT Last name: ");
scanf("%s", &st.lname);
printf("INPUT personal num: ");
scanf("%s", &st.num);
in= fopen("A.txt", "w");
fputs(st.fname, in);
fputs(st.lname, in);
fputs(st.num, in);
fclose(in);
in= fopen("A.txt", "r");
out=fopen("B.txt", "w");
fgets(st.fname, strlen(st.fname)+1,in);
strrev(st.fname);
fputs(st.fname, out);
printf("\n%s", st.fname);
fgets(st.lname, strlen(st.lname)+1, in);
strrev(st.lname);
fputs(st.lname, out);
printf("\n%s", st.lname);
fgets(st.num, strlen(st.num)+1, in);
strrev(&st.num);
fputs(st.num, out);
printf("\n%d", st.num);
fclose(in);
fclose(out);
return 0;
}
If you want to copy the data to a file, then you first need to put the data in some dynamic memory allocation and then after reversing the content required in dynamic memory, you need to copy it into your file.
this is the program to reverse the each word in given string
#include
#include
void reverse_string(char*);
void reverse_words(char*);
int main() {
char a[100];
gets(a);
reverse_words(a);
printf("%s\n", a);
return 0;
}
void reverse_words(char *s) {
char b[100], *t, *z;
int c = 0;
t = s;
while(*t) { //processing complete string
while(*t != ' ' && *t != '\0') { //extracting word from string
b[c] = *t;
t++;
c++;
}
b[c] = '\0';
c = 0;
reverse_string(b); // reverse the extracted word
z = b;
while (*z) { //copying the reversed word into original string
*s = *z;
z++;
s++;
}
while (*s == ' ') { // skipping space(s)
s++;
}
/*
* You may use if statement in place of while loop if
* you are assuming only one space between words. If condition is
* used because null terminator can also occur after a word, in
* that case we don't want to increment pointer.
* if (*s == ' ') {
* s++;
* }
*/
t = s; // pointing to next word
}
}
/*
* Function to reverse a word.
*/
void reverse_string(char *t) {
int l, c;
char *e, s;
l = strlen(t);
e = t + l - 1;
for (c = 0; c < l/2; c++) {
s = *t;
*t = *e;
*e = s;
t++;
e--;
}
}
Then you can try using fputc, i.e., reading char by char along with a loop to get your data line by line as 3 lines.
char *ch;
for(i=0;st.fname[i];i++)
{
ch=getc(st.fname[i]);
fputc(ch,in);
}
repeat the same even for st.lname and st.num

mips _Unwind_Backtrace on SIGSEGV

On a mips platform, I am trying to get Unwind work. Currently if I issue print_trace manually stack trace is correctly shown as below:
backtrace_helper 0x4b6958
backtrace_helper 0x4b6ab4
backtrace_helper 0x2ac2f628
Obtained 3 stack frames.
./v(print_trace+0x38) [0x4b6958]
./v(main+0x90) [0x4b6ab4]
/lib/libc.so.0(__uClibc_main+0x24c) [0x2ac2f628]
But when a SIGSEGV occurs, stack trace does not show correct function call sequence.
backtrace_helper 0x4b7a74
backtrace_helper 0x2ab9b84c
Obtained 2 stack frames.
./v(getLineIDByPhyIdx+0x3d8) [0x4b7a74]
/lib/libpthread.so.0(__new_sem_post+0x2c8) [0x2ab9b84c]
I am compiling with -g -fexceptions -rdynamic. Also I have seen How to generate a stacktrace when my gcc C++ app crashes in which 2nd answer mentiones about wrong address but when I set as he does but it only changes 2nd frame and rest is the same, code snippet is below:
caller_address = (void *) uc->uc_mcontext.gregs[30]; // Frame pointer (from wikipedia here)
fprintf(stderr, "signal %d (%s), address is %p from %p\n",
sig_num, strsignal(sig_num), info->si_addr,
(void *)caller_address);
size = backtrace(array, 50);
/* overwrite sigaction with caller's address */
array[1] = caller_address;
messages = backtrace_symbols(array, size);
Code:
int main(int argc, char *argv[]) {
registerSignalHandler(signalHandler);
print_trace();
{
// Seg Fault
int *p = NULL;
*p = 54;
}
}
void print_trace(void) {
void *array[10];
size_t size;
char **strings;
size_t i;
/* Get the address at the time the signal was raised from the EIP (x86) */
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
printf("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf("%s\n", strings[i]);
free(strings);
}
static _Unwind_Reason_Code
backtrace_helper (struct _Unwind_Context *ctx, void *a)
{
struct trace_arg *arg = a;
assert (unwind_getip != NULL);
/* We are first called with address in the __backtrace function. Skip it. */
if (arg->cnt != -1) {
arg->array[arg->cnt] = (void *) unwind_getip (ctx);
printf("backtrace_helper %p \n", arg->array[arg->cnt]);
}
if (++arg->cnt == arg->size)
return _URC_END_OF_STACK;
return _URC_NO_REASON;
}
/*
* Perform stack unwinding by using the _Unwind_Backtrace.
*
* User application that wants to use backtrace needs to be
* compiled with -fexceptions option and -rdynamic to get full
* symbols printed.
*/
int backtrace (void **array, int size)
{
struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
if (unwind_backtrace == NULL)
backtrace_init();
if (size >= 1)
unwind_backtrace (backtrace_helper, &arg);
return arg.cnt != -1 ? arg.cnt : 0;
}
void signalHandler( int sig, siginfo_t* siginfo, void* notused)
{
/* Print out the signal info */
signalInfo(sig, siginfo);
switch (sig) {
case SIGSEGV:
{
print_trace();
abort();
}
}
}
Frame pointer is practically never used on MIPS and obtaining backtrace without digging into symbols requires some heuristics.
Typical approach is to analyze code preceding current instruction pointer and try finding function prologue that adjusts SP. Using that info one can figure out location of preceding frame, etc.
See these slides for some of the gory details:
http://elinux.org/images/0/07/Intricacies_of_a_MIPS_Stack_Backtrace_Implementation.pdf