Ir para conteúdo
Fórum Script Brasil
  • 0

Preciso De Ajuda Com O Extern "c" No Dev-c++


Guest Alisson

Pergunta

Galera,

Estou usando um código disponível no site(), mas não estou tendo sucesso. Não tenho experiência com -o DEV-C++.

O erro de compilação é em relação as funções sgenrand e genrand, ambas estão sendo importadas do C como mostra a função abaixo.

extern "C" void sgenrand(unsigned long seed);

extern "C" unsigned long genrand(void);

Quem tiver conhecimento deste assunto, favor tentar compilar este código.

Obrigado

Link para o comentário
Compartilhar em outros sites

6 respostass a esta questão

Posts Recomendados

  • 0

Veja bem, a palavra chave 'extern' serve para usar recursos externos, seja váriaveis de outros escopos ou função de arquivos DLL, ou algo do gênero.

Essas funções, citadas acima, onde estão declaradas? Em uma DLL? Biblioteca C/C++? Pesquise e tente novamente, caso não consiga, poste aqui de novo, nesse tópico.

Falows!

P.S: pesquisei pouco sobre o tal (s) 'genrand', tem algo a ver com criptografia?? Estou sem tempo xD

Link para o comentário
Compartilhar em outros sites

  • 0

No caso é só incluir o arquivo 'mt19937-1.cpp', usando a diretiva #include. Eis o código do arquivo:

00001 /* A C-program for MT19937: Real number version (1999/10/28)    */
00002 /*   genrand() generates one pseudorandom real number (double)  */
00003 /* which is uniformly distributed on [0,1]-interval, for each   */
00004 /* call. sgenrand(seed) sets initial values to the working area */
00005 /* of 624 words. Before genrand(), sgenrand(seed) must be       */
00006 /* called once. (seed is any 32-bit integer.)                   */
00007 /* Integer generator is obtained by modifying two lines.        */
00008 /*   Coded by Takuji Nishimura, considering the suggestions by  */
00009 /* Topher Cooper and Marc Rieffel in July-Aug. 1997.            */
00010 
00011 /* This library is free software; you can redistribute it and/or   */
00012 /* modify it under the terms of the GNU Library General Public     */
00013 /* License as published by the Free Software Foundation; either    */
00014 /* version 2 of the License, or (at your option) any later         */
00015 /* version.                                                        */
00016 /* This library is distributed in the hope that it will be useful, */
00017 /* but WITHOUT ANY WARRANTY; without even the implied warranty of  */
00018 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.            */
00019 /* See the GNU Library General Public License for more details.    */
00020 /* You should have received a copy of the GNU Library General      */
00021 /* Public License along with this library; if not, write to the    */
00022 /* Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA   */ 
00023 /* 02111-1307  USA                                                 */
00024 
00025 /* Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura. */
00026 /* Any feedback is very welcome. For any question, comments,       */
00027 /* see http://www.math.keio.ac.jp/matumoto/emt.html or email       */
00028 /* matumoto@math.keio.ac.jp                                        */
00029 
00030 /* REFERENCE                                                       */
00031 /* M. Matsumoto and T. Nishimura,                                  */
00032 /* "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform  */
00033 /* Pseudo-Random Number Generator",                                */
00034 /* ACM Transactions on Modeling and Computer Simulation,           */
00035 /* Vol. 8, No. 1, January 1998, pp 3--30.                          */
00036 
00037 #include<stdio.h>
00038 
00039 /* Period parameters */  
00040 #define N 624
00041 #define M 397
00042 #define MATRIX_A 0x9908b0df   /* constant vector a */
00043 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
00044 #define LOWER_MASK 0x7fffffff /* least significant r bits */
00045 
00046 /* Tempering parameters */   
00047 #define TEMPERING_MASK_B 0x9d2c5680
00048 #define TEMPERING_MASK_C 0xefc60000
00049 #define TEMPERING_SHIFT_U(y)  (y >> 11)
00050 #define TEMPERING_SHIFT_S(y)  (y << 7)
00051 #define TEMPERING_SHIFT_T(y)  (y << 15)
00052 #define TEMPERING_SHIFT_L(y)  (y >> 18)
00053 
00054 static unsigned long muito[N]; /* the array for the state vector  */
00055 static int mti=N+1; /* mti==N+1 means muito[N] is not initialized */
00056 
00057 /* Initializing the array with a seed */
00058 void
00059 sgenrand(unsigned long seed)
00060 {
00061     int i;
00062 
00063     for (i=0;i<N;i++) {
00064          muito[i] = seed & 0xffff0000;
00065          seed = 69069 * seed + 1;
00066          muito[i] |= (seed & 0xffff0000) >> 16;
00067          seed = 69069 * seed + 1;
00068     }
00069     mti = N;
00070 }
00071 
00072 /* Initialization by "sgenrand()" is an example. Theoretically,      */
00073 /* there are 2^19937-1 possible states as an intial state.           */
00074 /* This function allows to choose any of 2^19937-1 ones.             */
00075 /* Essential bits in "seed_array[]" is following 19937 bits:         */
00076 /*  (seed_array[0]&UPPER_MASK), seed_array[1], ..., seed_array[N-1]. */
00077 /* (seed_array[0]&LOWER_MASK) is discarded.                          */ 
00078 /* Theoretically,                                                    */
00079 /*  (seed_array[0]&UPPER_MASK), seed_array[1], ..., seed_array[N-1]  */
00080 /* can take any values except all zeros.                             */
00081 void
00082 lsgenrand(unsigned long seed_array[])
00083     /* the length of seed_array[] must be at least N */
00084 {
00085     int i;
00086 
00087     for (i=0;i<N;i++) 
00088       muito[i] = seed_array[i];
00089     mti=N;
00090 }
00091 
00092 double /* generating reals */
00093 /* unsigned long */ /* for integer generation */
00094 genrand()
00095 {
00096     unsigned long y;
00097     static unsigned long mag01[2]={0x0, MATRIX_A};
00098     /* mag01[x] = x * MATRIX_A  for x=0,1 */
00099 
00100     if (mti >= N) { /* generate N words at one time */
00101         int kk;
00102 
00103         if (mti == N+1)   /* if sgenrand() has not been called, */
00104             sgenrand(4357); /* a default initial seed is used   */
00105 
00106         for (kk=0;kk<N-M;kk++) {
00107             y = (muito[kk]&UPPER_MASK)|(muito[kk+1]&LOWER_MASK);
00108             muito[kk] = muito[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
00109         }
00110         for (;kk<N-1;kk++) {
00111             y = (muito[kk]&UPPER_MASK)|(muito[kk+1]&LOWER_MASK);
00112             muito[kk] = muito[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
00113         }
00114         y = (muito[N-1]&UPPER_MASK)|(muito[0]&LOWER_MASK);
00115         muito[N-1] = muito[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
00116 
00117         mti = 0;
00118     }
00119   
00120     y = muito[mti++];
00121     y ^= TEMPERING_SHIFT_U(y);
00122     y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
00123     y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
00124     y ^= TEMPERING_SHIFT_L(y);
00125 
00126     return ( (double)y * 2.3283064370807974e-10 ); /* reals */
00127     /* return y; */ /* for integer generation */
00128 }

P.S: Retire os números de linha!

Dependências do arquivo: biblioteca 'stdio.h'

Nem precisa usar a palavra chave 'extern'. Falows! Qualquer coisa estamos aí!

Link para o comentário
Compartilhar em outros sites

  • 0

Cara eu tenho uma dúvida!

Já vi que você saca de Dll então resolvi perguntar.

Se a pessoa precisar fazer um DLL com uma biblioteca .h que NÃO seja padrão do Dev C++?

Tipo, o Dev C++ tem uma coleção enorme de bibliotecas .h . Mas vou precisar fazer uma DLL com um código que usa uma biblioteca .h que n faz parte dessa coleção do DEV. Como faço nesse caso?

Link para o comentário
Compartilhar em outros sites

  • 0

Ops me expressei errado! Terminei misturando mil coisas onde quero a solução de somente uma!

Reformulado a pergunta...

Já consegui fazer Dll's com arquivos de cabeçalho(headers) .h que fazem parte do pacote do DEV.

Mas tenho um projeto para entregar onde tenho que fazer uma DLL de um programa que usa um arquivo de cabeçalho que NÃO faz parte do pacote do Dev.

Como faço nesse caso?

------- teste.h ----------

#define funcion_H

#ifdef funcion_H

extern "C" __declspec(dllexport) void metodonativo(int numero);

extern "C" __declspec(dllexport) void metodonativotexto(char* texto);

#endif

------- teste.cpp --------

#include <stdio.h>

extern "C" __declspec(dllexport) void metodonativo(int numero){

printf("O numero foi: %d \n",numero);

}

extern "C" __declspec(dllexport) void metodonativotexto(char* texto){

printf("A string foi: %s \n",texto);

}

No exemplo acima fica tranquilo criar um DLL já que os arquivos de cabeçalhos usados fazem parte do pacote padrão do DEV (#include <stdio.h>).

Aprendi que para criar uma DLL é necessário criar os métodos que iram compor essa DLL salvando-os no formato .cpp . E criar um arquivo de cabeçalho contendo o protótipo desses métodos.

Só que eu tenho métodos criados que possuem códigos que estão atrelados a arquivos de cabeçalho que não fazem parte do pacote do DEV.

E ai? Como fazer o DEV enxergar uma Header que não faz parte do seu pacote para assim criar uma DLL?

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...